3

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');
Ajey
  • 7,924
  • 12
  • 62
  • 86

3 Answers3

5

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:

Community
  • 1
  • 1
Ruslan Bes
  • 2,715
  • 2
  • 25
  • 32
3

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

Community
  • 1
  • 1
topher
  • 14,790
  • 7
  • 54
  • 70
0
$criteria->order(array('RAND()'));
trejder
  • 17,148
  • 27
  • 124
  • 216
Deepak Mane
  • 105
  • 6
  • It is important to point out, that [using `ORDER BY RAND()` is wrong](http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/)! – trejder Jun 23 '15 at 07:30