mysql rand随机查询记录效率较低,本文通过实例做下对比分析。
select * from `table` order by rand() limit 5 不推荐
一个15万余条的库,查询5条数据,居然要8秒以上
官方手册:you cannot use a column with rand() values in an order by clause, because order by would evaluate the column multiple times.
搜索google:
复制代码 代码示例:
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;
产生连续的5条记录。
解决办法:
只能是每次查询一条,查询5次;15万条的表,查询只需要0.01秒不到
mysql的论坛:
复制代码 代码示例:
select *
from `table`
where id >= (select floor( max(id) * rand()) from `table` )
order by id limit 1;
需要0.5秒,速度不错
改写:
复制代码 代码示例:
select * from `table`
where id >= (select floor(rand() * (select max(id) from `table`)))
order by id limit 1;
效率提高,只有0.01秒
加上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;
最后在php中对这两个语句进行分别查询10次,
前者花费时间 0.147433 秒
后者花费时间 0.015130 秒