gpt4 book ai didi

mysql - SQL select from inner join where count 大于

转载 作者:可可西里 更新时间:2023-11-01 07:52:35 25 4
gpt4 key购买 nike

医生

doctorid (PK)doctorname

Patient

patientid (PK)patientnamedoctorid

I have the following query to get the doctors details with the number of patients that he/she consults. assume a patient has only one doctor to consult.

select d.doctorid,d.doctorname,count(p.patientid)
from doctor d
inner join patient p
on d.doctorid = p.doctorid
group by p.doctorid

现在我需要获取相同的信息,但仅限于拥有超过 1 个患者的医生。请给我一个查询建议。

最佳答案

使用HAVING clause

SELECT d.doctorid,
d.doctorname,
COUNT(p.patientid) AS patients
FROM doctor d
INNER JOIN patient p
ON d.doctorid = p.doctorid
GROUP BY
d.doctorid,
d.doctorname
HAVING patients > 1

我使用别名 (patients) 而不是 COUNT(p.patientid),因为 HAVING 子句允许这样做。但您也可以坚持使用 COUNT(p.patientid)
另外,我建议您在 GROUP BY 子句中使用所有非聚合列。
而且,如果您检索 doctorname,您可能不必检索 doctorid

关于mysql - SQL select from inner join where count 大于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22128236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com