【问题标题】:Count the repeats of foreign key of two tables统计两个表的外键重复次数
【发布时间】:2020-06-16 20:32:40
【问题描述】:

我有两张表国家(id,国家)和城市(id,城市,countryId)我想选择国家并显示有多少城市作为位置。

我试过了:

SELECT countryid, COUNT(*) AS locations
FROM Cities 
GROUP BY countryid

但它显示的是 countryid 而不是 country

【问题讨论】:

  • 加入 Country Table 并从 Country Table 中获取 Country 值。

标签: sql


【解决方案1】:

您需要按如下方式加入表格:

select c.country, count(*) as locations
from Country c
inner join Cities ci
on c.id = ci.countryId
group by c.id, c.country

我还将国家/地区包括在 group by 中,因为它出现在 select 子句中

【讨论】:

  • 很高兴我能帮上忙 c: 你介意接受我的回答吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多