An in depth analysis of the differences between order by group by and having in Mysql

  • 2020-05-17 06:48:04
  • OfStack

order by is the sorting of rows by default. order by must be followed by a list of sorted field names, which can be multiple field names.
group by means grouping. You must have an "aggregate function" to work with, and you need at least one grouping flag field.

What is an "aggregate function"?
sum(), count(), avg(), and so on are "aggregate functions"
The purpose of group and by is to summarize the data.

1, such as:
select unit name,count(employees' id),sum(employees' wages) form
group by unit name
Such operation result is with "unit name" the worker number that is classification mark statistic each unit and total wages.

In the order in which the sql command format is used, group by precedes order by.

The standard format of the select command is as follows:
SELECT select_list
[ INTO new_table ]
FROM table_source
[ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]

1. GROUP BY is a grouping query, and GROUP BY is used in conjunction with aggregate functions
group by has a rule that all columns following select that do not use aggregate functions must appear after group by (important)

For example, you have the following database table:
A B
1 abc
1 bcd
1 asdfg
If you have the following query statement (which is incorrect, see the previous rule)

select A,B from table group by A

The intent of this query is to get the following result (only 1, of course)
A B
abc
1 bcd

asdfg
How to change the three items on the right into one, so you need to use the aggregate function, as follows (here is the correct way to write it):

select A,count(B) as quantity from table group by A
The result is this
A number
1 3

2. Having

The function of the where clause is to remove the rows that do not conform to the where condition before grouping the query results, that is, to filter the data before grouping. The condition cannot contain clustering function, and the where condition is used to display specific rows.

The function of the having clause is to filter the groups that meet the conditions, that is, to filter the data after grouping. The conditions often contain clustering functions. The having conditions are used to display specific groups.

The having clause limiter is already on the columns and aggregate expressions defined in the SELECT statement. In general, you need to refer to the aggregate value by repeating the aggregate function expression in the HAVING clause, as you did in the SELECT statement. Such as:
SELECT A COUNT(B) FROM TABLE GROUP BY A HAVING COUNT(B) > 2


Related articles: