一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

mysql随机取数据的几种高效率方法

时间:2022-11-14 23:37:42 编辑:袖梨 来源:一聚教程网

1]普通方法, 效率太低

代码如下 复制代码

SELECT * FROM table ORDER BY rand() LIMIT 10;

[2] JOIN的方法:

代码如下 复制代码

SELECT *
FROM `table` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `table`) – (SELECT MIN(id) FROM `table`)) + (SELECT MIN(id) FROM `table`)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id LIMIT 10;


再把语句完善一下,加上MIN(id)的判断。我在最开始测试的时候,就是因为没有加上MIN(id)的判断,结果有一半的时间总是查询到表中的前面几行。
完整查询语句是:

代码如下 复制代码

SELECT * FROM `table`
WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`)) + (SELECT MIN(id) FROM `table`)))
ORDER BY id LIMIT 1;
SELECT *
FROM `table` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`))+(SELECT MIN(id) FROM `table`)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id LIMIT 1;


前者花费时间 0.147433 秒
后者花费时间 0.015130 秒
都是查询10咨物。

热门栏目