简体   繁体   中英

PHP Yii criteria select random records with limit

I have 1000 questions in the Question Model. How do I select 50 questions out of the 10000 randomly using Yii criteria ??

I am using Mysql as the 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:

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

(updated from @topher answer)

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.

In this case, refer to these answers:

The easiest solution: mysql's order by rand

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

However from http://jan.kneschke.de/projects/mysql/order-by-rand/

As soon as you have 10000 rows the overhead for sorting the rows becomes important.

How to efficiently get random rows has been already been answered: MySQL select 10 random rows from 600K rows fast

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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