这篇文章主要为大家详细介绍了MySQL优化取随机数据慢的方法,具有一定的参考价值,可以用来参考一下。
感兴趣的小伙伴,下面一起跟随四海网的小编小韵来看看吧!
前天因为工作需要我把从一个5W记录的数据库中随机抽取几条记录了,这里我是直接使用mysql rand by函数来直接,几千条记录没关系,但如果到了几万条感觉要几秒,这个就很慢了,下面小编与大家一起来看看mysql 取随机数据慢优化过程。代码如下:
SELECT * FROM tablename ORDER BY RAND() LIMIT 1
代码如下:
SELECT *
FROM 'table' AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM 'table')) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id ASC LIMIT 5;
代码如下:
SELECT *
FROM 'table'
WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM 'table' )
ORDER BY id LIMIT 1;
代码如下:
SELECT * FROM 'table'
WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM 'table')))
ORDER BY id LIMIT 1;
代码如下:
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(
# 最小值 + (1 至 最小与最大值差)
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;
代码如下:
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;
本文来自:http://www.q1010.com/177/9652-0.html
注:关于MySQL优化取随机数据慢的方法的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。
关键词:MYSQL
四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。