如果要在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查询中给定的非组字段不同。