Choose a random piece from 30 numbers from 200 numbers

I'm currently trying to make a piece of 30 numbers from a set of 200. For example, since this will be used with MySQL, I want to select 30 random images from a database of 200 images. I would like to have two numbers (high and low) that I could use in the limit statement, which will return 30 rows of data as follows: SELECT * FROM 'images' LIMIT 20,50 or SELECT * FROM 'images' LIMIT 10,40 . I know this probably sounds like a stupid question, although my brain is just crippling right now. All help is much appreciated! Thanks:)

+4
source share
3 answers

Just add ORDER BY RAND() to your query. This is "random enough".

  SELECT FOO FROM BAR ORDER BY RAND() LIMIT 30 
+3
source

Using ORDER BY RAND() is considered antipattern because you force the database to perform a full table scan and an expensive sort operation.

To take advantage of query caching, you can create a hybrid solution, for example:

 // take all image ids $keys = $db->query('SELECT image_id FROM images')->fetchALL(PDO::FETCH_COLUMN, 0); // pick 30 $random_keys = join(',', array_rand(array_flip($keys), 30)); // query those images only $values = $db->query("SELECT * FROM images WHERE image_id IN ($random_keys)")->fetchAll(PDO::FETCH_ASSOC); 

The above key request can be cached in PHP, so it can be used for more frequent requests. However , when your table is in the range of 100 thousand or more, I would suggest creating a separate table with image identifiers in a randomized order with which you can join the image table. You can fill this one or more times a day with ORDER BY RAND() .

+2
source

I would suggest using PHP array_rand() .

http://php.net/manual/en/function.array-rand.php

Put everything that you want to select from the array and let it select 20 entries for you. Then you can use any file names you want, without relying on the fact that they are in numerical order.

+1
source

All Articles