我有三张桌子
State(stateid, statename)
District(dict_id,dict_name,stateid)
city(city_id,dict_id,city_name)
我需要统计该州的州名和城市。是否可以在单个查询中获取Statename,district_count,city_count?
答案 0 :(得分:1)
这应该做:
SELECT S.Statename,
COUNT(DISTINCT C.dict_id) district_count,
COUNT(DISTINCT C.city_id) city_count
FROM City C
INNER JOIN District D
ON C.dict_id = D.dict_id
INNER JOIN State S
ON S.stateid = D.stateid
GROUP BY S.Statename
答案 1 :(得分:0)
您需要使用GROUP BY
。尝试这样的事情:
SELECT S.StateId, S.StateName, COUNT(DISTINCT D.Dict_Id) as DictCount, COUNT(DISTINCT C.City_Id) as CityCount
FROM State S
LEFT JOIN District D ON S.StateId = D.StateId
LEFT JOIN City C ON D.Dict_Id = C.Dict_Id
GROUP BT S.StateId, S.StateName
祝你好运。