如何从数据库中使用SQL查询获取国家和城市的数量?

时间:2017-08-04 15:16:05

标签: mysql

通过运行此查询:

select 
    c.name, count(s.name) as statecount,  
    sum(count(ci.name)) OVER() AS citycount 
from 
    countries c, states s, cities ci
where 
    ci.state_id = s.id 
    and s.country_id = c.id 
group by 
    s.name

我需要以这种方式获得输出:

Country => statecount => citycount

2 个答案:

答案 0 :(得分:2)

因为国家/地区可以有多个州,当您加入这些1到1和1到很多时,每个州都可以拥有多个城市。所以你需要独特的状态计数。城市数量已经是国家和州的独特之处,因此不需要区分。国家不是国家城市独有的地方,因此需要与众不同。当然,这假设您需要在每个国家/地区计算唯一状态。

SELECT c.name, count(distinct s.name) as statecount,  count(Ci.name) as CityCount
FROM countries c
INNER JOIN states s 
  on c.id = s.country_ID
INNER JOIN cities ci
  ON s.id = ci.state_id
GROUP BY C.name

或保持旧式连接符号:

SELECT c.name, count(distinct s.name) as statecount,  count(ci.name) citycount 
FROM countries c,states s,cities ci
WHERE ci.state_id = s.id 
  and s.country_id = c.id 
GROUP BY s.name

请考虑以下示例:http://rextester.com/ZGYF56786

或图片下方

查看国家,州和城市之间何时出现联接。由于加入到城市,状态变得重复,使得状态在该列中不再是唯一的,通过做一个不同的我们只返回2个状态而不是7个,每个记录一个。

+-----+------------+-------------+
| USA | Illinois   | Chicago     |
| USA | Illinois   | Springfield |
| USA | Illinois   | Peoria      |
| USA | California | LosAngeles  |
| USA | California | Sacramento  |
| USA | California | SanDeigo    |
| USA | California | Hollywood   |
| USA | California | Oakland     |
|-----|------------|-------------|
|Name | statecount | Citycount   |
| USA | 2          | 7           | <-- Is this result correct? (i hope so)
| USA | 7          | 7           | <-- or this one? (then why bother just count(*) and only 1 count needed.
+-----+------------+-------------+

我认为你想要第一个结果,因为在列出的美国表和7个城市中只有2个州。

答案 1 :(得分:0)

你不需要Over。这应该只是一个简单的分组。

SELECT c.name, COUNT(s.name) AS statecount,  COUNT(ci.name) AS citycount 
FROM countries c
     JOIN states s
        ON c.id = s.country_id
     JOIN cities ci
        ON s.id = ci.state_id
GROUP BY c.name