How MySQL optimizes group by

Source: Internet
Author: User

  

The most general way to execute a GROUP BY clause is to scan the entire table first and then create a new temporary table in which all rows for each group should be contiguous and finally use the temporary table to locate the group

and apply the aggregation function (if there is an aggregation function). In some cases, MySQL can get results by accessing the index without creating a temporary table. The EXPLAIN output of this type of query shows Extra

The value of the column is Using index for group-by.

One. Loose Index Scanning

1. Meet the conditions

    • The query is for a table.
    • GROUP by uses the leftmost prefix of the index.
    • You can only use the min () and Max () aggregate functions, and they all point to the same column.

2. Example

Table T1 (C1,C2,C3,C4) has an index of IDX (C1,C2,C3):

Const Const CONSTconst GROUP by C1, C2; 

Examples of conditions not satisfied:

1. In addition to Min () or Max (), there are other cumulative functions, for example:     SELECT C1, SUM (C2) from T1 GROUP by C1;
2. The fields in the GROUP by clause do not reference the beginning of the index, for example:
     SELECT c1,c2 from T1 GROUP by C2, C3;
3. The query references part of the keyword following the GROUP by section, and there is no equality equal to the constant, for example: SELECT c1,c3 from T1 GROUP by C1, C2;

Two. Compact Index Scan

If the loose index scan condition is not met, performing group by can still not create a temporary table. If there is a scope condition in the WHERE clause, the method reads only the keywords that meet these conditions.

Otherwise, an index scan is performed. The method reads the scope defined by the WHERE clause.

1. There is a vulnerability in GROUP by, but it has been overridden by the condition C2 = ' a ' .      = ' A ' GROUP by C1,C3;
2. Group by does not satisfy the leftmost prefix, but there is a condition that provides a constant for the element:= ' A ' group by C2,C3;

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.