mysql> select countrycode as total fromCity where id<10;
+-------+
| total |
+-------+
| AFG |
| AFG |
| AFG |
| AFG |
| NLD |
| NLD |
| NLD |
| NLD |
| NLD |
+-------+
9 rows in set (0.00 sec)
mysql> select countrycode,count(*) astotal from City where id<10 group by countrycode;
+-------------+-------+
| countrycode | total |
+-------------+-------+
| AFG | 4 |
| NLD | 5 |
+-------------+-------+
2 rows in set (0.00 sec)
把相同的字段进行分组,并对分组内的数据进行统计。
使用having过滤分组
Having用于分组之后过滤数据,where用于分组之前选择数据。
mysql> select countrycode,count(*) astotal from City where id<101 group by countrycode;
+-------------+-------+
| countrycode | total |
+-------------+-------+
| AFG | 4 |
| AGO | 5 |
| AIA | 2 |
| ALB | 1 |
| AND | 1 |
| ANT | 1 |
| ARE | 5 |
| ARG | 32 |
| ASM | 2 |
| ATG | 1 |
| DZA | 18 |
| NLD | 28 |
+-------------+-------+
12 rows in set (0.01 sec)
mysql> select countrycode,count(*) astotal from City where id<101 group by countrycode having count(*)>10;
+-------------+-------+
| countrycode | total |
+-------------+-------+
| ARG | 32 |
| DZA | 18 |
| NLD | 28 |
+-------------+-------+
3 rows in set (0.00 sec)
先选择数据,然后分组,然后having过滤数据。
在group by后求和
mysql> select countrycode,count(*) astotal from City where id<10 group by countrycode with rollup;
+-------------+-------+
| countrycode | total |
+-------------+-------+
| AFG | 4 |
| NLD | 5 |
| NULL | 9 |
+-------------+-------+
3 rows in set (0.00 sec)
在最后增加一行显示求和结果。
多字段分组
先按照第一个字段进行分组,按照分组内容进行第二个字段的分组。
限制查询结果行数量
mysql> select * from City limit 3;
+----+----------+-------------+----------+------------+
| ID | Name | CountryCode | District | Population |
+----+----------+-------------+----------+------------+
| 1| Kabul | AFG | Kabol | 1780000 |
| 2| Qandahar | AFG | Qandahar| 237500 |
| 3| Herat | AFG | Herat | 186800 |
+----+----------+-------------+----------+------------+
3 rows in set (0.00 sec)