Possible Duplicate:
How do I select random rows in MySQL?
Okay, so I have a table storing game data, and it’s reaching 7 million rows.
I need an efficient way to select a random row.
Here’s what I’ve tried so far:
SELECT `id` FROM `information` ORDER BY RAND() LIMIT 1;
Fairly logical query. Takes 8 seconds to run. Completely unacceptable.
Second attempt:
SELECT FLOOR(RAND()*COUNT(`id`)) INTO @target FROM `information`;
SELECT `id` FROM `information` LIMIT @target,1;
Fails on syntax error with the variable in the second query.
Third attempt:
SELECT `id` FROM (SELECT `id` FROM `information`) `a` ORDER BY RAND() LIMIT 1
The idea here is to strip out all the other fields, since they’re unnecessary bulk. It half-works, bringing the time down to 6 seconds. Still far too long, though.
And… I’m out. I can’t think of any other ways (but it is 1 AM…), so any suggestions would be much appreciated. Thanks!
If you are using
INNODBengine, an article I read before suggested that it is better to count the number of records first usingCOUNT(*)because the engine does not cache the count of the table unlikeMyISAM,DISCLAIMER: the query i used performed exactly as needed on 3m records. I don’t know how it behaves on 7m records though.