我有医生和医院的数据库,由医院医生表加入。
我必须列出城镇,每个城镇的医院数量,但只有医院超过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行。
HOSPITAL
医院医生
我该如何撰写此查询?
答案 0 :(得分:2)
你可以用基本相同的结构做你想做的事情:
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
而不是=
,因为子查询可能会返回多行。答案 1 :(得分:0)
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
答案 2 :(得分:0)
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