简体   繁体   English

带有两个表的 MySQL 子查询 count 和 group by

[英]MySQL subquery with two tables count and group by

I have database of doctors and hospital joined by hospitaldoctor table.我有医院医生表加入的医生和医院数据库。

I have to List town, amount of hospitals in each town, but only hospitals which have more than 5 doctors.我必须列出城镇,每个城镇的医院数量,但只有医生超过 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 

this is my query but MySQL returns me that subquery returns more than 1 row.这是我的查询,但 MySQL 返回给我,子查询返回超过 1 行。

HOSPITAL医院

医院

HOSPITAL DOCTOR医院医生

医院医生

How i should write this query?我应该如何写这个查询?

You can do what you want with basically the same structure:你可以用基本相同的结构做你想做的事:

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 ;

Note the following:请注意以下事项:

  • You want to use in not = , because the subquery could return more than one row.您想in not =使用,因为子查询可能返回多于一行。
  • The subquery should be returning the hospital id not the count.子查询应该返回医院 id 而不是计数。
  • Use table aliases and qualified column names whenever a table refers to more than one table.每当一个表引用多个表时,使用表别名和限定的列名。
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
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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM