My database has 300 rows at the moment and propably will increse to about 5000 rows during the next years. I want to know how I can select 20 rows randomly best.
I found here MySQL select 10 random rows from 600K rows fast (where it is again refered to http://jan.kneschke.de/projects/mysql/order-by-rand/) that the following code produces a random selection very fast:
SELECT name
FROM random AS r1 JOIN
(SELECT (RAND() *
(SELECT MAX(id)
FROM random)) AS id)
AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1
so in php I tried the following to get 20 rows:
$anfrage = "SELECT name
FROM random AS r1 JOIN
(SELECT (RAND() *
(SELECT MAX(id)
FROM random)) AS id)
AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 20";
$ergebnis=$db->query($anfrage)
or die($db->error);
while($zeile=mysqli_fetch_assoc($ergebnis))print_r($zeile);
But when I run the script I wont get 20 rows most of the time. Actually, the probability to pick 20 different rows out of 300 is about 48,8%.
Can I change the above code to get really 20 rows very quick?