MySQL随机查询一条记录语法及优化
发表于2011-02-20 14:02:36阅读43059次
About selecting random rows from a MySQL table:
SELECT * FROM tablename ORDER BY RAND() LIMIT 1
works for small tables, but once the tables grow larger than 300,000 records or so this will be very slow because MySQL will have to process ALL the entries from the table, order them randomly and then return the first row of the ordered result, and this sorting takes long time. Instead you can do it like this (atleast if you have an auto_increment PK):
SELECT MIN(id), MAX(id) FROM tablename;
Fetch the result into $a
$id=rand($a[0],$a[1]);
SELECT * FROM tablename WHERE id>='$id' LIMIT 1
如何实现优先随机查询特定条件的数据呢?
即,使得随机查询更倾向于特定记录,比如ID值较小的记录。这个问题很有意思哈,我觉得。