我有医生和医院的数据库,还有医院医生表。
我必须列出每个镇的医院数量,但只有有超过5名医生的医院。
SELECT hospital.town, count(town)
FROM hospital
WHERE hospital.id = (
SELECT count(hospital_id)
FROM hospital_doctor GROUP BY hospital_id
HAVING count(hospital_id)>5 )
GROUP BY town 这是我的查询,但是MySQL会返回我的子查询返回超过1行。
医院

医院医生

我应该如何写这个查询?
发布于 2018-02-22 12:32:44
你可以用基本相同的结构做你想做的事:
Select h.town, count(*)
from hospital h
where h.id in (select hd.hospital_id
from hospital_doctor hd
group by hd.hospital_id
having count(*) > 5
)
group by h.town ;请注意以下事项:
in而不是=,因为子查询可能返回多个行。发布于 2018-02-22 12:44:13
Select hospital.town, count(town)
from hospital
where
hospital.id in (
select hospital_id
from hospital_doctor
group by hospital_id
having count(hospital_id)>5
)
group by town发布于 2018-02-22 12:45:45
SELECT h.town, count(h.town)
FROM
(
SELECT hospital_id
FROM hospital_doctor GROUP BY hospital_id
HAVING count(doctor_id)>5
) s1
left outer join hospital h on (s1.hospital_id=h.id)
GROUP BY h.town https://stackoverflow.com/questions/48927457
复制相似问题