Examples explain MySQL Group By (ii)

mysql group by using the method of Example explain

In MySQL GROUP BY statement for a certain field or inquiry packet, and returns the first, field duplicate records is each team ( no sorting ) first inside.

This article describes the mysql group by using the method and the need to pay attention to you by way of example, interested friends can reference.

 

Now there is such a data table book

 

Examples of the basic group by

We grouped queries on city field

SELECT * FROM book GROUP BY city

The results are as follows:

 

As can be seen, group by group according to a city, because a book table has three different city value, so there will be three lines of data, and returns only the results of the same city set first data .

 

 

group by multiple fields

The following look at group by followed by multiple fields

SELECT * FROM book GROUP BY city,last_name

The results are as follows:

 

group by more than one field followed by how to understand it?

GROUP BY  city, last_name是指所有city, last_name项只要有一个不相同就会分一个组的。因为上面book表中第二行数据与第三行数据的city和last_name相同,所以会舍弃其中的一行数据,一般都是舍弃后面一行,所以第二行数据保留了。如下图(先进行city分组如红色,在进行last_name分组如蓝色,然后都取第一条数据)

 

 

 

 

group by与聚合函数

一般情况下,group by都会与聚合函数一起使用,以达到复杂的数据查询要求。

比如我们要根据city分组后,获取每一组有多少条数据

SELECT *,count(*) FROM book GROUP BY city

结果为:

 

 

group by having

group by having用于指示被选择的行必须满足的条件

比如,我们根据city分组,但我们只需要查询出每一组的数据条数大于1的

SELECT *,count(*) FROM book GROUP BY city having count(*)>1

结果集为:

 

 

 

原文地址 http://www.manongjc.com/article/1065.html

在原文基础上有改动

 

Guess you like

Origin www.cnblogs.com/111testing/p/11334217.html