小编给大家分享一下MySQL百分位数计算如何进行优化,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
主要是采用存储过程,在中间计算结果中,增加了一个索引
原来的SQL
select t5.query_time,t5.ts,t2.v from (
select query_time,total,v, floor(1+(total-1)*v) rn
from (
select query_time,count(*) total from t group by query_time
) t3, (select 0.71 v,1 seq union all select 0.81,2 union all select 0.91,3) t4
)
t2 inner join (
select
query_time,
case when @gid=query_time then @rn:=@rn+1 when @gid:=query_time then @rn:=1 end rn,
ts
from (
select * from t ,(select @gid:='',@rn:=0) vars order by query_time,ts
) t1
) t5 on (t2.query_time=t5.query_time and t2.rn=t5.rn )
改进为存储过程
drop procedure p;
delimiter $$
create procedure p()
begin
drop table if exists tmp_result;
create temporary table tmp_result(
query_time date,
rn int,
ts float,
key(query_time,rn)
) engine =memory;
insert ignore into tmp_result
select
query_time ,
case when @gid=query_time then @rn:=@rn+1 when @gid:=query_time then @rn:=1 end rn,
ts
from (
select * from t ,(select @gid:='',@rn:=0) vars order by query_time,ts
) t1 ;
select t5.query_time,t5.ts,t2.v from (
select query_time,total,v, floor(1+(total-1)*v) rn
from (
select query_time,count(*) total from t group by query_time
) t3, (select 0.71 v,1 seq union all select 0.81,2 union all select 0.91,3) t4
)
t2 inner join tmp_result t5 on (t2.query_time=t5.query_time and t2.rn=t5.rn );
end $$
delimiter ;
call p
使用存储过程 一般 11秒 左右
以上是“MySQL百分位数计算如何进行优化”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!