首页 > 其他 > 详细

一条统计Group By语句优化

时间:2014-02-18 08:32:15      阅读:338      评论:0      收藏:0      [点我收藏+]

在检查慢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 < 1392480000
 GROUP BY platform, channel;
执行时间:

bubuko.com,布布扣

耗时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 < 1392480000
 GROUP BY platform, channel order by null;


执行时间:
bubuko.com,布布扣

耗时55.22秒


执行计划:

bubuko.com,布布扣


结论:
默认情况下,MySQL对所有GROUP BY col1,col2...的字段进行排序。如果查询包括GROUP BY,想要避免排序结果的消耗,则可以指定ORDER By NULL禁止排序。


参考手册:

bubuko.com,布布扣




本文出自 “贺春旸的技术专栏” 博客,请务必保留此出处http://hcymysql.blog.51cto.com/5223301/1359738

一条统计Group By语句优化

原文:http://hcymysql.blog.51cto.com/5223301/1359738

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!