随机读取数据库记录,搜索发现很多人都使用 order by rand() 来达到该目的,这是mysql提供的功能。但是实际上存在非常严重的性能问题。 如果表里记录不多,偶尔用一下也可以。但是如果数据多的话,就会凸显出查询的性能问题。
随机查询5条记录:
SELECT * FROM `table` ORDER BY RAND() LIMIT 5;
在数十万记录的表里,这样的查询要好几秒的时间。下面采用JOIN的方式改进一下:
SELECT *
FROM `table` AS t1 JOIN (SELECT FLOOR(RAND() * (SELECT MAX(id) FROM `table`)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id ASC LIMIT 5;
FROM `table` AS t1 JOIN (SELECT FLOOR(RAND() * (SELECT MAX(id) FROM `table`)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id ASC LIMIT 5;
这样得到连续的5条记录。要不联续的记录,可以连续查询几次,每次limit 1条。这淡水比较推荐,SQL语句比较清晰,效率也不错。
还有,可以这样的:
SELECT * FROM `table`
WHERE id >= (SELECT FLOOR(RAND() * (SELECT MAX(id) FROM `table`))) ORDER BY id LIMIT 1;
WHERE id >= (SELECT FLOOR(RAND() * (SELECT MAX(id) FROM `table`))) ORDER BY id LIMIT 1;
其他更复杂的实现,淡水无视之。