MySQL GROUP BY 语句
GROUP BY 语句根据一个或多个列对结果集进行分组。
在分组的列上我们可以使用 COUNT, SUM, AVG,等函数。
GROUP BY 语法
SELECT 字段 FROM 表名 WHERE 条件 GROUP BY 字段;
实例演示
以下是实例要用到的表数据:
mysql> select * from mydb_jianshu;
+------------+----------------------------+----------------+-----------------+
| jianshu_id | jianshu_title | jianshu_author | submission_date |
+------------+----------------------------+----------------+-----------------+
| 2 | 学习网络安全从0到1 | Fangdm | 2018-02-09 |
| 3 | MySQL基础 | Fangdm | 2018-02-09 |
| 4 | 安全测试 | Fangdm | 2018-03-01 |
| 5 | GROUP BY | Fangdm | 2018-03-02 |
| 6 | TEST | Fang | 2018-03-02 |
| 7 | TEST | Fang | 2018-03-02 |
+------------+----------------------------+----------------+-----------------+
6 rows in set (0.00 sec)
接下来我们使用 GROUP BY 语句 将数据表按 jianshu_author 进行分组,并统计每个 作者 有多少条记录:
mysql> select jianshu_author,count(*) as "count(*)/条数" from mydb_jianshu group by jianshu_author;
+----------------+-----------------+
| jianshu_author | count(*)/条数 |
+----------------+-----------------+
| Fang | 2 |
| Fangdm | 4 |
+----------------+-----------------+
2 rows in set (0.00 sec)
我们也可以指定被选中行必须满足条件
比如,我们根据 jianshu_author 分组,但我们只需要查询出数据条数大于 2 的。
mysql> select jianshu_author,count(*) as "count(*)/条数" from mydb_jianshu group by jianshu_author having count(*)>2;
+----------------+-----------------+
| jianshu_author | count(*)/条数 |
+----------------+-----------------+
| Fangdm | 4 |
+----------------+-----------------+
1 row in set (0.00 sec)
注:group by having用于指示被选择的行必须满足的条件