MySQL子查询有两个表计数和分组依据

时间:2018-02-22 12:29:33

标签: mysql sql

我有医生和医院的数据库,由医院医生表加入。

我必须列出城镇,每个城镇的医院数量,但只有医院超过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

HOSPITAL

医院医生

HOSPITAL DOCTOR

我该如何撰写此查询?

3 个答案:

答案 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而不是=,因为子查询可能会返回多行。
  • 子查询应该返回医院ID而不是计数。
  • 只要表引用多个表,就使用表别名和限定列名。

答案 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