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

mysql中随机查询取值效率优化

2024/3/8 18:02:47发布15次查看
在mysql中随机查询数据是一个比较常用的功能,但是这个随机查询功能如果没使用好你的数据库就会卡死,特别到了几十万,上百万数据时更要注意了,下面我来介绍mysql中随机查询取值效率优化.
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;
该用户其它信息

VIP推荐

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