gpt4 book ai didi

MySQL查询问题

转载 作者:行者123 更新时间:2023-11-29 22:25:42 24 4
gpt4 key购买 nike

这是我的查询:

  SELECT count(*) as total, dp.name,dp.id,dp.description, dp.avatar 
FROM `doctors` d
right join departments dp on d.department_id = dp.id
group by d.department_id

我有表格:医生和科室。我想提取每个科室的医生总数。这个查询工作正常,它返回我所有有医生的部门,但不返回没有医生的部门。不知何故,我想显示所有部门和总数,它代表属于某个部门的医生。我怎样才能做到这一点?

这是医生表:enter image description here这是部门表 enter image description here

最佳答案

您可以尝试一下:

SELECT 
(SELECT count(*) FROM doctors d WHERE d.department_id = dp.id) AS total,
dp.*
FROM departments AS dp

如果您想使用JOIN,请尝试以下操作:

SELECT 
COUNT(d.department_id) AS total,
dp.*
FROM departments AS dp
LEFT JOIN doctors AS d ON dp.id = d.department_id
GROUP BY dp.id

关于MySQL查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30284996/

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