在检查慢sql时,发现一条统计sql执行过慢,如下:原sqlselectplatform,channel,count(distinct(platformuserid))ascntfrom(selectplatform,channel,platformuser
在检查慢sql时,,发现一条统计sql执行过慢,如下:
原sql
select platform, channel, count(distinct(platformuserid)) as cnt from(
select platform, channel, platformuserid, min(inserttimestamp) as rtime
from tsz_user
group by platform, channel, platformuserid
) a where a.rtime >= 1392393600 and a.rtime
group by platform, channel;
执行时间:
耗时2分33秒
优化后sql
select platform, channel, count(distinct(platformuserid)) as cnt from(
select platform, channel, platformuserid, min(inserttimestamp) as rtime
from tsz_user
group by platform, channel, platformuserid order by null
) a where a.rtime >= 1392393600 and a.rtime
group by platform, channel order by null;
执行时间:
耗时55.22秒
执行计划:
结论:
默认情况下,mysql对所有group by col1,col2...的字段进行排序。如果查询包括group by,想要避免排序结果的消耗,则可以指定order by null禁止排序。
参考手册:
本文出自 “贺春旸的技术专栏” 博客,请务必保留此出处