mysql使用rand()进行随机查询
代码如下 复制代码
1 order by rand() limit x
随机mysql查询效率极其低下,今晚本人就遇到几个wordpress插件的作者,随机取值,竟然都是直接
代码如下 复制代码
1 order by rand()
这也太坑爹了,数据一多,譬如你有个5万~10万,加上每天几千ip,那效率就跟蜗牛似的。不信你试试。这是严重不
负责任的随机查询。
后来百度找了一个方法
代码如下 复制代码
select *
from table
where id >= (
select ceil( rand( ) * (
select max( id )
from table ) ) )
limit 1
或者
select *
from table
where id >= (
select round( rand( ) * (
select max( id )
from table ) ) )
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 1
这样就快了很多哦,但是这个方法,会导致大部分的取值都在1/2前范围内,需要重新改造下:
代码如下 复制代码
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;