mysql随机取数据的几种高效率方法
时间:2021-07-01 10:21:17
帮助过:96人阅读
我用最简单的也是常用的方法来看看,下面再介绍高效的mysql随机数据的方法,有需要的朋友可以参考一下。
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咨物。