我有3个表:COUNTRY
,STATE
,CITY
这是我的Country
表,有两列:
CountryID, Name
这是我的State
表:
这是我的City
表:
我想使用连接查询根据country
表检索州和城市的数量。
答案 0 :(得分:0)
跳过你的问题没有被问到好的事实 - 尝试这个查询,它应该适合你:
WITH
tab_a AS (
SELECT c.countryid, COUNT (s.stateid) AS state_num
FROM country c
LEFT JOIN state s ON c.countryid = s.countryid
GROUP BY c.countryid
),
tab_b AS (
SELECT c.countryid, COUNT (cc.cityid) city_num
FROM country c
LEFT JOIN state s ON c.countryid = s.countryid
LEFT JOIN city cc ON s.stateid = cc.stateid
GROUP BY c.countryid
)
SELECT a.countryid,
a.state_num,
b.city_num
FROM tab_a a JOIN tab_b b ON a.countryid=b.countryid