If you read the MySQL manual you might have seen the ORDER BY
RAND() to randomize the the rows and using the LIMIT 1 to just
take one of the rows.
SELECT name
FROM random
ORDER BY RAND()
LIMIT 1;
This example works fine and is fast if you only when let's say
1000 rows. As soon as you have 10000 rows the overhead for
sorting the rows becomes important. Don't forget: we only sort to
throw nearly all the rows away.
I never liked it. And there are better ways to do it. Without a
sorting. As long as we have a numeric primary key.
For the first examples we assume the be ID is starting at 1 and
we have no holes between 1 and the maximum value of the ID.
move the work into the application
First idea: We can simplify the whole job if we calculate the ID
beforehand in the application.
SELECT MAX(id) FROM random;
## generate random id in application
SELECT name FROM random WHERE id = …
[Read more]