I have seen random rows pulled using queries like this, which are quite inefficient for large data sets.
SELECT id FROM table ORDER BY RANDOM() LIMIT 1
I have also seen various other RDBMS-specific solutions that don't work with MySQL.
The best thing I can think of doing off-hand is using two queries and doing something like this.
- Get the number of rows in the table. MyISAM tables store the row count so this is very fast.
- Calculate a random number between 0 and rowcount - 1.
- Select a row ordered by primary key, with a LIMIT randnum, 1
Here's the SQL:
SELECT COUNT(*) FROM table;
SELECT id FROM table LIMIT randnum, 1;
Does anyone have a better idea?