我有餐桌部门和员工。
架构就像

department(id, name)
employee(id,depid,salary)


我需要获取每个部门的员工人数。
我在mysql中的查询就像

select d.depname,count(e.id)
from employe as e left join department as d on d.depid
where e.depid=d.depid group by d.depid;


但是结果集中只包含有员工的部门。
我需要那些零员工的部门本身为零。

最佳答案

只是交换表名,

SELECT  d.name,
        COUNT(e.id) totalEmployeeCount
FROM    department AS d
        LEFT JOIN employee AS e
            ON e.depid = d.id
GROUP   BY d.id;


要进一步获得有关联接的知识,请访问以下链接:


Visual Representation of SQL Joins

09-11 03:25