我有以下两个表:
TABLE: area
*City_ID *Number Name
-------- ------- ----
SUR 1 Fleetwood
SUR 2 Whalley
SUR 3 Guildford
SUR 4 Newton
SUR 5 Cloverdale
SUR 6 South Surrey
ABB 1 Abbotsford East
ABB 2 Abbotsford West
ABB 3 Aberdeen
ABB 4 Bradner
ABB 5 Central Abbotsford
ABB 6 Matsqui
ABB 7 Poplar
ABB 8 Sumas Mountain
ABB 9 Sumas Prairie
TABLE: city
*ID Name
--- ----
SUR Surrey
ABB Abbotsford
LAN Langley
使用以下声明:
SELECT DISTINCT area.City_ID, city.Name
FROM area
INNER JOIN city
WHERE area.City_ID = city.ID
我明白了:
SELECT:
City_ID city.Name
------- ---------
SUR Surrey
ABB Abbotsford
但是如何选择以下内容:
SELECT:
City_ID city.Name area_COUNT
------- --------- ----------
SUR Surrey 6
ABB Abbotsford 9
其中area_COUNT
是area
中每个对应City_ID
的行数?
答案 0 :(得分:2)
使用GROUP BY
代替DISTINCT
:
SELECT city.City_ID, city.Name, COUNT(*)
FROM area
INNER JOIN city
WHERE area.City_ID = city.ID
GROUP BY city.ID
答案 1 :(得分:1)
您还应该在分组
中添加名称SELECT area.City_ID, city.Name, count(*) as area_COUNT
FROM area
INNER JOIN city
WHERE area.City_ID = city.ID
GROUP BY area.City_ID,City.Name
答案 2 :(得分:0)
在最后添加分组
SELECT area.City_ID, city.Name, count(*) as area_COUNT
FROM area
INNER JOIN city
WHERE area.City_ID = city.ID
GROUP BY area.City_ID
答案 3 :(得分:0)
使用GROUP BY而不是DISTINCT:
SELECT city.City_ID,city.Name,COUNT(*) 从地区 INNER JOIN city WHERE area.City_ID = city.ID GROUP BY city.ID