简体   繁体   English

PHP Yii标准选择带限制的随机记录

[英]PHP Yii criteria select random records with limit

I have 1000 questions in the Question Model. 我在问题模型中有1000个问题。 How do I select 50 questions out of the 10000 randomly using Yii criteria ?? 如何使用Yii标准随机选择10000个问题中的50个问题?

I am using Mysql as the Db 我使用Mysql作为Db

So far I have tried with the following 到目前为止,我已尝试过以下内容

$criteria = new CDbCriteria;
$criteria->limit = 50;
$criteria->select = array('id');
$criteria->addCondition('chapter = xyz');

If you are using MySQL then it's: 如果您使用的是MySQL,那么它是:

$criteria->order = 'RAND()';

(updated from @topher answer) (从@topher回复更新)

Using this technique on a large number of rows will take a long time ( source ): 在大量行上使用此技术需要很长时间( ):

As soon as you have 10000 rows the overhead for sorting the rows becomes important. 只要有10000行,排序行的开销就变得很重要。

In this case, refer to these answers: 在这种情况下,请参考以下答案:

The easiest solution: mysql's order by rand 最简单的解决方案:rand的mysql命令

$criteria->order('RAND()');

However from http://jan.kneschke.de/projects/mysql/order-by-rand/ 但是来自http://jan.kneschke.de/projects/mysql/order-by-rand/

As soon as you have 10000 rows the overhead for sorting the rows becomes important. 只要有10000行,排序行的开销就变得很重要。

How to efficiently get random rows has been already been answered: MySQL select 10 random rows from 600K rows fast 如何有效地获取随机行已经得到了回答: MySQL快速从600K行中选择10个随机行

$criteria->order(array('RAND()'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM