这篇文章主要为大家详细介绍了MySQL中RAND()随便查询记录效率问题和解决办法分享,具有一定的参考价值,可以用来参考一下。
感兴趣的小伙伴,下面一起跟随四海网的小编小韵来看看吧!
最近由于需要大概研究了一下MYSQL的随机抽取实现方法。举个例子,要从tablename表中随机提取一条记录,大家一般的写法就是:SELECT * FROM tablename ORDER BY RAND() LIMIT 1。代码如下:
#auther: 小强(占卜师)
#date: 2008-03-31
create table randnumber
select -1 as number
union
select -2
union
select -3
union
select -4
union
select -5
union
select 0
union
select 1
union
select 2
union
select 3
union
select 4
union
select 5
#得到随机数
#auther: 小强(占卜师)
#date: 2008-03-31
select number
from randnumber order by rand() limit 1
代码如下:
SELECT ROUND((0.5-RAND())*2*5)
#注释
#0.5-rand()可以得到-0.5 至 +0.5的随机数
#(0.5-rand())*2可以得到-1 至 +1的随机数
#(0.5-rand())*2*5可以得到-5 至 +5的随机数
#ROUND((0.5-RAND())*2*5)可以得到-5 至 +5的随机整数
代码如下:
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(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;
本文来自:http://www.q1010.com/177/10239-0.html
注:关于MySQL中RAND()随便查询记录效率问题和解决办法分享的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。
关键词:MYSQL
四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。