首页 > Mysql rand()函数效率问题

Mysql rand()函数效率问题

查询语句

SELECT * FROM tablename ORDER BY RAND() LIMIT 100

查询效率极其低下,解释如下:

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 * FROM 'table'
WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM 'table'))) 
ORDER BY id LIMIT 100;

通过 max(id) * rand()来确定随机数,不过个人认为这个办法有很大的局限
1)
RAND()*MAX(id)的值如果是最大id值,那怎么可能查的出来100条数据
2)
再者,如果id不是连续的,比如 1,2,3,1000,那这个查询也有问题

难道RAND()没有很好的解决方案么


MySQL中ORDER BY RAND的确有性能问题,因为MySQL必需遍历所有的记录才能得到结果。
如果你只要100个,你可以考虑先select all id,从中随机挑选100个id,然后再select by id,这样会比较快,当然对于太大的dataset这样依然会有潜在的性能问题。
如果你的记录集实在太大,比如超过100M,那么你必须用一些变通的手段,比如定期随机给所有记录加上一个随机的RANK之类。

【热门文章】
【热门文章】