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

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

问题描述

使用 Laravel Eloquent,如何从前 100 行中随机抽取 10 行(按日期排序).

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

例如,我有这个:

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

我该如何更改它,以便从所选的 100 行中随机抽取 10 行?有没有办法做到这一点,这样我就不必检索 100 行?

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() 真的很慢,所以我不建议你使用它.

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

2 - take(100)->random() 解决方案总是将 100 行放入内存,然后才会得到 10 个随机行.您提到当集合中只有 5 个项目时会出现错误,因此请改用以下代码:

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 - 如果此查询在您的应用中经常执行,我建议您创建附加列 sort 并使用计划任务更新此列.每天或几个小时将 1 到 100 个整数设置为 sort 列的值.将这些数字应用于表中最新的 100 行,其他行设置为 0.

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.

然后您将能够通过快速查询获得最新的 radnom 10 行:

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天全站免登陆