我有表部门和员工。 架构就像,
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;
但结果集仅包含其中包含员工的部门。 我需要那些拥有0名员工的部门为零。
答案 0 :(得分:6)
只需交换表名,
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;
要进一步了解联接,请访问以下链接:
答案 1 :(得分:1)
select d.depname,count(e.id) from employee as e
right join department as d on d.depid = e.depid
group by d.depid;