簡體   English   中英

帶有兩個表的 MySQL 子查詢 count 和 group by

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

我有醫院醫生表加入的醫生和醫院數據庫。

我必須列出城鎮,每個城鎮的醫院數量,但只有醫生超過 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 行。

醫院

醫院

醫院醫生

醫院醫生

我應該如何寫這個查詢?

你可以用基本相同的結構做你想做的事:

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 not =使用,因為子查詢可能返回多於一行。
  • 子查詢應該返回醫院 id 而不是計數。
  • 每當一個表引用多個表時,使用表別名和限定的列名。
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