我有一個表像下:選擇和計數,其中結果是在其他地方
ID | Name | Type | State | County
-------------------------------------------------------------------
1 | Rheinland-Pfalz | State | Rheinland-Pfalz | NULL
2 | Trier | City | Rheinland-Pfalz | NULL
3 | Alzey-Worms | County | Rheinland-Pfalz | Alzey-Worms
4 | Alzey | City | Rheinland-Pfalz | Alzey-Worms
5 | Worms | City | Rheinland-Pfalz | Alzey-Worms
6 | Lorem | County | Rheinland-Pfalz | Lorem
7 | Ipsum | City | Rheinland-Pfalz | Lorem
現在我想獲得國家「萊茵蘭 - 普法爾茨」及其包括城市和所有countie自由城市內所有的縣。
祝願結果:
ID | Name | Type | Included
-------------------------------------------------------------------
2 | Trier | City | NULL
3 | Alzey-Worms | County | 2
6 | Lorem | County | 1
我的查詢:
select a.id, a.name, a.type,
(select count(*) from data where a.type="city" AND b.county=a.county) as included
from data as a, data as b
WHERE a.location_type='county' AND a.state = 'Rheinland-Pfalz' OR a.type='city' AND a.gmap_area1 = 'Rheinland-Pfalz' AND a.county IS NULL
order by a.name asc
我的結果:
ID | Name | Type | Included
-------------------------------------------------------------------
3 | Alzey-Worms | County | 0
3 | Alzey-Worms | County | 0
3 | Alzey-Worms | County | 0
3 | Alzey-Worms | County | 0
3 | Alzey-Worms | County | 0
....等等
請問上面的查詢工作? –
@ AT-2016:不,我用結果更新了帖子... – chack