当我不使用mysql GROUP BY时,我只得到一行数据

When I don't use mysql GROUP BY, I only get one row of data

这里是 mysql 的新手。我正在使用 mysql 版本 5.6.25-enterprise-commercial-advanced,并且我有表格

mysql> select * from Department;
+-------+--------------+
| DepID | DepName      |
+-------+--------------+
|     1 | English      |
|     2 | Math         |
|     3 | History      |
|     4 | French       |
|     5 | Geography    |
|     6 | Drawing      |
|     7 | Architecture |
+-------+--------------+

mysql> select * from Student;
+--------+----------+------------+-------+
| StudID | StudName | StudentAge | DepID |
+--------+----------+------------+-------+
|      1 | Alice    |         21 |     2 |
|      2 | Alfred   |         20 |     3 |
|      3 | Henry    |         19 |     3 |
|      4 | Jacobs   |         22 |     5 |
|      5 | Bob      |         20 |     4 |
|      6 | Shane    |         22 |     4 |
|      7 | Linda    |         24 |     4 |
|      8 | Stacy    |         20 |     1 |
|      9 | Wolfred  |         21 |     2 |
|     10 | Sandy    |         25 |     1 |
|     11 | Colin    |         18 |     1 |
|     12 | Maria    |         19 |     3 |
|     13 | Ziva     |         20 |     5 |
|     14 | Mark     |         23 |     5 |
|     15 | Fred     |         25 |     2 |
|     16 | Vic      |         25 |  NULL |
|     17 | Nick     |         25 |  NULL |
+--------+----------+------------+-------+

我正在使用查询:

SELECT Department.DepName, AVG(Student.StudentAge) AS AvgStudAge
FROM Student
RIGHT JOIN Department
ON Student.DepID = Department.DepID;

只会产生一行:

+---------+------------+
| DepName | AvgStudAge |
+---------+------------+
| English |    21.2667 |
+---------+------------+

...但我觉得我也应该得到所有其他行,DepName 列给我类似 "English" 或 "Math" 的内容,相关的总年龄是平均年龄与该部门相关的所有学生。为什么英语只有 return 行?

我实际上发现在我之前查询的末尾插入以下代码行 GROUP BY DepName; 可以得到我想要的结果,但我不明白为什么我必须 GROUP BY anything。

如有任何澄清,我们将不胜感激!

在您的查询中:

SELECT Department.DepName, AVG(Student.StudentAge) AS AvgStudAge
FROM Student
RIGHT JOIN Department
ON Student.DepID = Department.DepID;

通过使用像 AVG 这样的聚合而不同时使用 GROUP BY,SQL 将其视为所有返回数据的平均值,与部门无关。

MySql 在返回的单行上显示的 DepName 是任意返回的第一个值。除了 MySql,符合 ANSI 标准的 RDBMS 将为此查询引发错误,因为所有选择的列都必须引入聚合(如果没有 GROUP BY),或者所有非聚合列必须在 GROUP BY 子句中(分组时)。 MySql 在这方面的容忍度令人讨厌,这可能会导致错误。

每个系的平均学生年龄示例:

SELECT Department.DepName, AVG(Student.StudentAge) AS AvgStudAge
FROM Student
RIGHT JOIN Department
ON Student.DepID = Department.DepID
GROUP BY Department.DepName;

所有学生的平均学生年龄:

SELECT AVG(Student.StudentAge) AS AvgStudAge
FROM Student;

Examples of aggregates with / without GROUP BY here

只需要在最后GROUP by Department.DepID加上Group By,你就会得到所有部门的平均值