且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel-在应用``order by''后在特定列中随机选择n个包含相同值的行

更新时间:2023-02-05 20:17:59

您可以使用子查询来执行此操作,但是根据我的经验,它们需要花费更多的时间来执行,然后执行一些较小的操作(如果索引正确).另外,您可以更好地控制限制和调试问题.

You could do this with subqueries, but in my experience they take more time to execute then a few smaller ones (if they are indexed correctly). Also, you have more control over the limits and debugging issues.

$top_ads = Ads::whereCol2('topad')->inRandomOrder()->limit(5)->get();
$urgent_ads = Ads::whereCol2('urgent')->inRandomOrder()->limit(10)->get();
$bump_ads = Ads::whereCol2('bump')->inRandomOrder()->limit(2)->get();

这将创建您的查询,然后您可以对它们的集合进行任何操作.合并它们,对其重新排序,等等.

This will create your queries and after that you can do whatever you want with their collections. Combine them, reorder them, etc.