Possible duplicate:
quick random row selection from large table in mysql
I have seen random rows being pulled using such queries that are pretty inefficient for large datasets.
SELECT id FROM table ORDER BY RANDOM() LIMIT 1
I also saw various other RDBMS-specific solutions that do not work with MySQL.
The best I can think of doing this is to use two queries and do something like this.
- Get the number of rows in the table. MyISAM tables store row counts, so it is very fast.
- Compute a random number between 0 and rowcount - 1.
- Select the row ordered by the primary key using LIMIT randnum, 1
Here's the SQL:
SELECT COUNT(*) FROM table; SELECT id FROM table LIMIT randnum, 1;
Does anyone have a better idea?
mysql random
David Sep 26 '08 at 21:58 2008-09-26 21:58
source share