我的问题与SQL GROUP BY
原语的语义有关。
假设我们有以下关系(用户):
+----+------+---------------+-----+
| id | name | country | age |
+----+------+---------------+-----+
| 1 | Foo | Brazil | 20 |
| 2 | Bar | Japan | 20 |
| 3 | Baz | Brazil | 22 |
| 4 | Quz | Brazil | 18 |
+----+------+---------------+-----+
我期望以下虚拟查询:
SELECT name, country, avg(age)
FROM Users
GROUP BY country
返回四个元组,因为我们在SELECT
投影中使用了非分组属性:
+------+---------------+-----+
| name | country | age |
+------+---------------+-----+
| Foo | Brazil | 20 |
| Bar | Japan | 20 |
| Baz | Brazil | 20 |
| Quz | Brazil | 20 |
+------+---------------+-----+
然而,它产生了以下元组:
+------+---------------+-----+
| name | country | age |
+------+---------------+-----+
| Foo | Brazil | 20 |
| Bar | Japan | 20 |
+------+---------------+-----+
为什么?
编辑:发现Why can't you mix Aggregate values and Non-Aggregate values in a single SELECT?回答了这个问题。