您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

mysql随机取数据的几种高效率方法

2024/6/14 13:46:38发布23次查看
我用最简单的也是常用的方法来看看,下面再介绍高效的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咨物。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product