Detailed explanation of the group by statement of mysql

1. Query statement group by grouping

  • The group by keyword can group query results according to one or more fields
  • group by is generally used in combination with Mysql aggregate functions
  • If you need to specify conditions to filter the grouped result set, you need to combine the having keyword; reason: where cannot be used in conjunction with aggregate functions and where is executed before group by

The syntax format of group by:

GROUP BY  <字段名>[,<字段名>,<字段名>]

2. There are multiple fields behind group by

If there are multiple fields after group by, it is actually similar to the multiple fields after order by. For example: group by a, b; multiple pieces of data shared by fields a and b will be merged, and different data will not be merged. Specific examples are as follows:

3. Having after group by

The having after group by is to filter and screen the grouped fields again, generally using an aggregation function. The following example: (group the field a, and the number before grouping must be greater than 1)

select a, 
    count(1),
    max(b)
from f 
where a like 'X%'
group by a 
    having count(a) > 1

Or you can filter non-grouping fields with aggregate functions

4. The HAVING clause can contain one or more predicates connected with AND and OR

5. After using the HAVING sentence, use the difference of count (*) after the select

 

SELECT COUNT(*),Ssex FROM Student GROUP BY Ssex;

 

6. The keyword ALL after group by

The keyword All after group by will be grouped only after it is filtered by the where condition. Then the keyword All is to display all the data that does not meet the conditions.

Seven, the keywords CUBE and ROLLUP after group by

The first thing to explain is that the Group By All statement cannot be used together with the CUBE and ROLLUP keywords.

8. Precautions for using field aliases

Since the execution sequence of mysql is as follows:

from
on
join
where
group by
select
having
order by
limit

It can be seen from the above: the field alias after select can only be used after the select is executed.

Guess you like

Origin blog.csdn.net/m0_69057918/article/details/132146466