mysql ORDER BY RAND() 语句优化

SELECT id FROM table ORDER BY RAND() LIMIT n;

优化为:

SELECT id FROM table t1 JOIN (SELECT RAND() * (SELECT MAX(id) FROM table) AS nid) t2 ON t1.id > t2.nid LIMIT n;

SELECT id FROM table t1 JOIN (SELECT round(RAND() * (SELECT MAX(id) FROM table)) AS nid FROM table LIMIT n) t2 ON t1.id = t2.nid;

 

posted @ 2020-05-06 14:35  李小加  阅读(345)  评论(0编辑  收藏  举报