这是因为没有GROUP BY子句,MySQL返回的输出可能会误导。我们在下面的“学生”表上给出以下示例,以进行演示-
mysql> Select * from Student; +------+---------+---------+-----------+ | Id | Name | Address | Subject | +------+---------+---------+-----------+ | 1 | Gaurav | Delhi | Computers | | 2 | Aarav | Mumbai | History | | 15 | Harshit | Delhi | Commerce | | 20 | Gaurav | Jaipur | Computers | +------+---------+---------+-----------+ 4 rows in set (0.00 sec) mysql> Select count(*), Name from Student; +----------+--------+ | count(*) | name | +----------+--------+ | 4 | Gaurav | +----------+--------+ 1 row in set (0.00 sec)
从上面的查询结果可以看出,它返回组函数COUNT(*)的输出作为表中的总行数,但是字段“名称”中的值“ Gaurav”具有误导性,因为我们在什么基础上执行,要么是该列的第一个值,要么是多次存储在该列中,MySQL会返回它。
现在,如果我们将使用GROUP BY子句编写此查询,则结果集如下-
mysql> Select count(*), name from student GROUP BY id; +----------+---------+ | count(*) | name | +----------+---------+ | 1 | Gaurav | | 1 | Aarav | | 1 | Harshit | | 1 | Gaurav | +----------+---------+ 4 rows in set (0.00 sec)
从上面的结果集中可以看出,借助GROUP BY子句,我们得到了有意义的输出。