我有一个如下表:
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
现在我希望得到州内的所有县和#34; Rheinland-Pfalz"及其所包含的城市和所有免费城市。
希望的结果:
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
....等等
答案 0 :(得分:1)
不要害羞使用括号
SELECT
a.id,
a.name,
a.type,
(SELECT COUNT(*) FROM data
WHERE type='city' AND county=a.county) AS included
FROM data AS a
WHERE
a.state='Rheinland-Pfalz' AND
(a.type='county' OR (a.type='city' AND a.county IS NULL));
答案 1 :(得分:0)
你可以尝试使用group子句的一种方法 - 未经测试:
select count(*) from data where type in ('state','County') where
state = 'Rheinland-Pfalz' group by type,state;
另外要考虑的是ID或详细字段级别值不会出现在计数
中