【发布时间】:2015-02-18 15:17:27
【问题描述】:
给定以下表结构:
countries: id, name
regions: id, country_id, name, population
cities: id, region_id, name
...这个查询...
SELECT c.name AS country, COUNT(DISTINCT r.id) AS regions, COUNT(s.id) AS cities
FROM countries AS c
JOIN regions AS r ON r.country_id = c.id
JOIN cities AS s ON s.region_id = r.id
GROUP BY c.id
如何添加regions.population 值的SUM 来计算国家人口?求和时我只需要使用每个区域的值一次,但是未分组的结果对于每个区域(该区域的城市数量)都有多行。
示例数据:
mysql> SELECT * FROM countries;
+----+-----------+
| id | name |
+----+-----------+
| 1 | country 1 |
| 2 | country 2 |
+----+-----------+
2 rows in set (0.00 sec)
mysql> SELECT * FROM regions;
+----+------------+-----------------------+------------+
| id | country_id | name | population |
+----+------------+-----------------------+------------+
| 11 | 1 | region 1 in country 1 | 10 |
| 12 | 1 | region 2 in country 1 | 15 |
| 21 | 2 | region 1 in country 2 | 25 |
+----+------------+-----------------------+------------+
3 rows in set (0.00 sec)
mysql> SELECT * FROM cities;
+-----+-----------+---------------------------------+
| id | region_id | name |
+-----+-----------+---------------------------------+
| 111 | 11 | City 1 in region 1 in country 1 |
| 112 | 11 | City 2 in region 1 in country 1 |
| 121 | 12 | City 1 in region 2 in country 1 |
| 211 | 21 | City 1 in region 1 in country 2 |
+-----+-----------+---------------------------------+
4 rows in set (0.00 sec)
带有示例数据的期望输出:
+-----------+---------+--------+------------+
| country | regions | cities | population |
+-----------+---------+--------+------------+
| country 1 | 2 | 3 | 25 |
| country 2 | 1 | 1 | 25 |
+-----------+---------+--------+------------+
我更喜欢不需要更改 JOIN 逻辑的解决方案。
this post 的 accepted solution 似乎在我正在寻找的附近,但我无法弄清楚如何将其应用于我的问题。
我的解决方案
SELECT c.id AS country_id,
c.name AS country,
COUNT(x.region_id) AS regions,
SUM(x.population) AS population,
SUM(x.cities) AS cities
FROM countries AS c
LEFT JOIN (
SELECT r.country_id,
r.id AS region_id,
r.population AS population,
COUNT(s.id) AS cities
FROM regions AS r
LEFT JOIN cities AS s ON s.region_id = r.id
GROUP BY r.country_id, r.id, r.population
) AS x ON x.country_id = c.id
GROUP BY c.id, c.name
注意:我的实际查询要复杂得多,与国家、地区或城市无关。这是说明我的问题的最小示例。
【问题讨论】:
-
确定该查询?您选择城市名称为“国家”,并按城市 ID 分组?
-
您需要每个地区或国家的人口吗?
-
我的错误。我已经更正了别名。我想要这个国家的人口。
标签: mysql sql select group-by sum