从前100名中取10个随机行 [英] Take 10 random rows from the top 100

查看:86
本文介绍了从前100名中取10个随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Laravel Enloquent,如何从前100名(按日期排序)中的10个随机行。



例如,我有这样的:

  $ comments =评论:: orderBy('created_at','DESC')
- > take(100)
- > inRandomOrder()
- > get();

如何更改此选项,以便从100个选择中选择10个随机行?有没有办法做到这一点,我不需要检索100行?

解决方案

1 - inRandomOrder()真的很慢,所以我不建议你使用它。



2 - take(100) - > random()解决方案将始终将$ code> 100 行存入内存中,然后只能获得10个随机行。你提到你收到一个错误,只有5个项目在colleciton,所以使用这个代码:

  $ comments = Comment :: latest() - > take(100) - > get(); 
$ count = $ comments-> count()> 9? 10:$ comments-> count();
$ random = $ comments-> random($ count);

3 - 如果您的应用程序中经常执行此查询,我建议您创建其他列 sort 并使用计划任务更新此列。每天或几个小时将1到100个整数设置为 sort 列的值。将这些数字应用于表中的100个最新行,其他行设置为0。



然后,您可以使用快速查询获取最新的radnom 10行: / p>

  $ comments = Comment :: orderBy('sort') - > take(10) - > get() 

看起来复杂的解决方案,但在高负载系统上,这是最好的选择之一。 >

Using Laravel Eloquent, how can I take 10 random rows from the top 100 (sorted by date).

For example, I have this:

$comments = Comment::orderBy('created_at', 'DESC')
    ->take(100)
    ->inRandomOrder()
    ->get();

How can I change this so that it takes 10 random rows from the 100 selected? Is there a way to do this such that I don't have to retrieve 100 rows?

解决方案

1 - inRandomOrder() is really slow, so I wouldn't recommend you to use it.

2 - take(100)->random() solution will always get 100 rows into the memory and only then will get 10 random rows. You mentioned you're getting an error when there are only 5 items in the colleciton, so use this code instead:

$comments = Comment::latest()->take(100)->get();
$count = $comments->count() > 9 ? 10 : $comments->count();
$random =  $comments->random($count);

3 - If this query is being executed really often in you app, I would recommend you to create additional column sort and update this column with scheduled task. Set 1 to 100 integers as values of the sort column every day or few hours. Apply these numbers to the 100 latest rows in the table, other rows set to 0.

Then you'll be able to get latest radnom 10 rows with fast query:

$comments = Comment::orderBy('sort')->take(10)->get();

It looks like complicated solution, but on high load system it's one of the best options.

这篇关于从前100名中取10个随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆