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

时间:2015-07-22 05:21:11

标签: mysql relational-database

这里的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列给我一些类似“英语”或“数学”的东西,相关的聚合年龄是与之相关的所有学生的平均年龄部门。为什么它只为英语返回一行?

我实际上发现在我之前的查询结尾处插入以下代码行GROUP BY DepName;可以得到我想要的内容,但我不明白为什么我应该使用GROUP BY。

任何澄清都将不胜感激!

2 个答案:

答案 0 :(得分:0)

在您的查询中:

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

答案 1 :(得分:-1)

只需在上一个GROUP by Department.DepID中添加分组依据,您就可以获得所有部门的平均值