Optimization of a statistical GroupBy statement

Source: Internet
Author: User
When checking slow SQL statements, it is found that execution of a statistical SQL statement is too slow, as follows: the original SQLSELECTplatform, channel, COUNT (DISTINCT (platformUserId) ascntFROM (SELECTplatform, channel, platformUser

When checking slow SQL statements, it is found that execution of a statistical SQL statement is too slow, as follows: the original SQLSELECTplatform, channel, COUNT (DISTINCT (platformUserId) ascntFROM (SELECTplatform, channel, platformUser

When checking slow SQL statements, it is found that execution of a statistical SQL statement is too slow, as shown below:


Original 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;

Execution time:

2 minutes 33 seconds


SQL statement after optimization

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;


Execution time:

Time: 55.22 seconds


Execution Plan:


Conclusion:

BY default, MySQL sorts all group by col1, col2. .. fields. If the query includes group by, you can specify ORDER By NULL to disable sorting to avoid consumption of sorting results.


Reference manual:




This article is from the "hechun's technical column" blog. Be sure to keep this source

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.