SELECT * FROM table_name AS r1 JOIN (SELECT ROUND(RAND() *(SELECT MAX(id) FROM table_name)) AS id) AS r2 WHERE r1.id = r2.id ORDER BY r1.id ASC LIMIT 5;
执行效率需要0.02 sec.可惜的是,只有mysql 4.1.*以上才支持这样的子查询.
下面是其它网友的补充:
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com/bianchengyuyan/)select id from zhyx_items order by rand() 这样效率太低了
优化sql语句之后:
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com/bianchengyuyan/)SELECT t1.id FROM zhyx_items AS t1 JOIN (SELECT ROUND(RAND() *((SELECT MAX(id) FROM zhyx_items)-(SELECT MIN(id) FROM zhyx_items))+(SELECT MIN(id) FROM zhyx_items)) AS id) AS t2 WHERE t1.id = t2.id ORDER BY t1.id LIMIT 0,5;