您好,欢迎访问一九零五行业门户网

mysql 随机查询数据_MySQL

bitscn.com
在mysql中查询5条不重复的数据,使用以下:
1 select * from `table` order by rand() limit 5
就可以了。但是真正测试一下才发现这样效率非常低。一个15万余条的库,查询5条数据,居然要8秒以上
搜索google,网上基本上都是查询max(id) * rand()来随机获取数据。
1 select * 2 from `table` as t1 join (select round(rand() * (select max(id) from `table`)) as id) as t2 3 where t1.id >= t2.id 4 order by t1.id asc limit 5;
但是这样会产生连续的5条记录。解决办法只能是每次查询一条,查询5次。即便如此也值得,因为15万条的表,查询只需要0.01秒不到。
上面的语句采用的是join,mysql的论坛上有人使用
1 select * 2 from `table` 3 where id >= (select floor( max(id) * rand()) from `table` ) 4 order by id limit 1;
我测试了一下,需要0.5秒,速度也不错,但是跟上面的语句还是有很大差距。总觉有什么地方不正常。
于是我把语句改写了一下。
1 select * from `table` 2 where id >= (select floor(rand() * (select max(id) from `table`))) 3 order by id limit 1;
这下,效率又提高了,查询时间只有0.01秒
最后,再把语句完善一下,加上min(id)的判断。我在最开始测试的时候,就是因为没有加上min(id)的判断,结果有一半的时间总是查询到表中的前面几行。
完整查询语句是:
1 select * from `table` 2 where id >= (select floor( rand() * ((select max(id) from `table`)-(select min(id) from `table`)) + (selectmin(id) from `table`))) 3 order by id limit 1;4 5 select * 6 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 7 where t1.id >= t2.id 8 order by t1.id limit 1;
最后对这两个语句进行分别查询10次,
前者花费时间 0.147433 秒
后者花费时间 0.015130 秒
看来采用join的语法比直接在where中使用函数效率还要高很多。
-------------------------------------------------
以上来自:http://blog.csdn.net/zxl315/article/details/2435368
ps:上面的查出来的数据是连续的,如果想要得到非连续数据则可以用如下方法:
1. 能过exists子查询得到几个随机数,再从中取得数据(不推荐,50w条数据耗时1秒多,只能说这是一种方法来参考)
1 select distinct2 c.id, c.`name`, c.age, c.address3 from4 contact as c5 where6 exists (select 1 from (select 7 round(rand() * (select max(id) - min(id) from contact) + (select min(id) from contact)) as id 8 from contact limit 40) as t1 where t1.id = c.id)9 limit 4;
2. 通过join来得到随机数据,50w条数据耗时0.001秒
1 select distinct2 c.id, c.`name`, c.age, c.address3 from4 contact as c5 join (select 6 round(rand() * (select max(id) - min(id) from contact) + (select min(id) from contact)) as id 7 from contact limit 40) as t2 on c.id = t2.id8 limit 4;
上面数据为本地测试,mysql版本为5.5.27
bitscn.com
其它类似信息

推荐信息