Organizational Research By

Surprising Reserch Topic

Question:how to Get 10 rows from a query


I have a query which consists of joins and has an output of about 30,000+ records. I would like to get 10 random rows from these records without using SQL command rand().

I tried looping through the records and put them in an array and shuffle (get the 1st 10 after shuffle) them but it takes about 8-12 seconds to generate. I would like to reduce this processing time at all cost.

How will I accomplish this?

asked Sep 13, 2013 in MYSQL by rajesh
edited Sep 12, 2013
0 votes
16 views



Related Hot Questions

4 Answers

0 votes
To get a completely random set of random keys, try the array_rand() function:

$random_keys = array_rand($array, 10);

To get a random set of consecutive array elements, you can also try array_slice() with a random offset argument:

$random_elements = array_slice($array, mt_rand(0,count($array)-9), 10);
answered Sep 13, 2013 by rajesh
edited Sep 12, 2013
0 votes

Ok if you don't want to use RAND() do a much faster select of just the id column first then select only the 10 rows you want

  • Select the IDs into $idarray (SELECT id FROM table)
  • Shuffle and slice $idarray
  • $sql="SELECT ... WHERE id IN (".implode(', ', $idarray).")";

 

answered Sep 13, 2013 by rajesh
edited Sep 12, 2013
0 votes
To get a completely random set of random keys, try the array_rand() function:

$random_keys = array_rand($array, 10);

To get a random set of consecutive array elements, you can also try array_slice() with a random offset argument:

$random_elements = array_slice($array, mt_rand(0,count($array)-9), 10);
answered Sep 13, 2013 by rajesh
edited Sep 12, 2013
0 votes

Ok if you don't want to use RAND() do a much faster select of just the id column first then select only the 10 rows you want

  • Select the IDs into $idarray (SELECT id FROM table)
  • Shuffle and slice $idarray
  • $sql="SELECT ... WHERE id IN (".implode(', ', $idarray).")";

 

answered Sep 13, 2013 by rajesh
edited Sep 12, 2013

...