我无法在某些情况下加入 3 个表
I can't join 3 tables with some condition
我有 3 个表:
- 省份
- 城市
- 住宅
以下是这些表的列:
Provinces
:
id , name , status
Cities
:
id , province_id , name , status
Residences
:
id , province_id , city_id , name , status
我想要所有省份,以及该省拥有的城市数量,当城市至少有 1 个住宅时。
例如:#1省有10个城市,每个城市有10个住宅。
但只有5个城市有city.status = 1
并有住宅,只有3个城市有status = 1
的住宅。
所以返回的数据应该是:
Province 1 - 3 cities (count cities.id)
省份 1 的所有 3 个城市至少有 1 个状态为 1 的住所
如何查询?
我不会用SQL3
抱歉我的英语不好
谢谢
SELECT
p.name,
COUNT(DISTINCT c.id) AS city_count
FROM
residences AS r
INNER JOIN
cities AS c
ON c.id = r.city_id
INNER JOIN
provinces AS p
ON p.id = r.province_id
WHERE
r.status = 1
AND c.status = 1
AND p.status = 1
GROUP BY
p.name
或者...
SELECT
p.name,
COUNT(*) AS city_count
FROM
cities AS c
INNER JOIN
provinces AS p
ON p.id = c.province_id
WHERE
c.status = 1
AND p.status = 1
AND EXISTS (
SELECT *
FROM residences
WHERE status = 1
AND city_id = c.id
AND province_id = p.id
)
GROUP BY
p.name
我有 3 个表:
- 省份
- 城市
- 住宅
以下是这些表的列:
Provinces
:
id , name , status
Cities
:
id , province_id , name , status
Residences
:
id , province_id , city_id , name , status
我想要所有省份,以及该省拥有的城市数量,当城市至少有 1 个住宅时。
例如:#1省有10个城市,每个城市有10个住宅。
但只有5个城市有city.status = 1
并有住宅,只有3个城市有status = 1
的住宅。
所以返回的数据应该是:
Province 1 - 3 cities (count cities.id)
省份 1 的所有 3 个城市至少有 1 个状态为 1 的住所
如何查询?
我不会用SQL3
抱歉我的英语不好
谢谢
SELECT
p.name,
COUNT(DISTINCT c.id) AS city_count
FROM
residences AS r
INNER JOIN
cities AS c
ON c.id = r.city_id
INNER JOIN
provinces AS p
ON p.id = r.province_id
WHERE
r.status = 1
AND c.status = 1
AND p.status = 1
GROUP BY
p.name
或者...
SELECT
p.name,
COUNT(*) AS city_count
FROM
cities AS c
INNER JOIN
provinces AS p
ON p.id = c.province_id
WHERE
c.status = 1
AND p.status = 1
AND EXISTS (
SELECT *
FROM residences
WHERE status = 1
AND city_id = c.id
AND province_id = p.id
)
GROUP BY
p.name