如何在 MySQL SELECT 查询中将分组函数与非分组字段结合使用?
如果想在 SELECT 查询中将分组函数与非分组字段结合使用,我们必须使用 GROUP BY 子句。其常规语法如下
语法
SELECT group_function1,…, non-group-column1,… from table_name GROUP BY column_name;
示例
mysql> Select COUNT(*), id from Student GROUP BY id; +----------+------+ | COUNT(*) | id | +----------+------+ | 1 | 1 | | 1 | 2 | | 1 | 15 | | 1 | 17 | | 1 | 20 | +----------+------+ 5 rows in set (0.00 sec) mysql> Select COUNT(*), address from Student GROUP BY id; +----------+---------+ | COUNT(*) | address | +----------+---------+ | 1 | Delhi | | 1 | Mumbai | | 1 | Delhi | | 1 | Shimla | | 1 | Jaipur | +----------+---------+ 5 rows in set (0.00 sec)
GROUP BY 子句后的字段可以与 SELECT 查询中给出的非分组字段不同。
广告