表DEPARTMEnT
表雇员
运营部门没有任何员工。所以,我相信查询也会检索到行(图像1):
Department_ID = 10,Department_Name = Operations,Employee = 0
为什么不会发生?
SELECT EMPLOYEE.Department_ID, DEPARTMENT.Department_Name, Count(*) AS Employees
FROM EMPLOYEE right JOIN DEPARTMENT ON DEPARTMENT.Department_ID = EMPLOYEE.Department_ID
GROUP BY DEPARTMENT.Department_Name,.EMPLOYEE.Department_ID
答案 0 :(得分:1)
默认join
是inner join
,只返回两侧至少找到一行的行。将join
替换为left join
以检索没有员工的部门。
示例代码:
SELECT e.Department_ID
, d.Department_Name
, count(e.Employee_ID) AS Employees
FROM Department d
LEFT JOIN
Employee e
ON d.Department_ID = e.Department_ID
GROUP BY
d.Department_ID
, d.Department_Name
答案 1 :(得分:1)
由于您关心此查询的主要数据来自DEPARTMENT表,您可能需要考虑将查询重写为:
SELECT DEPARTMENT.Department_ID, DEPARTMENT.Department_Name, Count(EMPLOYEE.Employee_ID) As Employees
FROM DEPARTMENT
LEFT JOIN EMPLOYEE ON EMPLOYEE.Department_ID = DEPARTMENT.Department_ID
GROUP BY DEPARTMENT.Department_ID, DEPARTMENT.Department_Name
答案 2 :(得分:1)
这应该可以解决问题。如果您首先拥有RIGHT JOIN
表,那么可以放入EMPLOYEE
,但这不是很好的原因是因为很快您的查询将开始混合{{1即使对于经验丰富的SQL专业人员来说,它也会成为非常难以阅读的。}和LEFT
联接。通过坚持使用RIGHT
,您可以保持查询的可维护性和可理解性。 (在极少数情况下LEFT JOIN
可能会简化具有复杂优先顺序的查询,但我只做了两次以避免必须在连接组周围添加括号。)
RIGHT JOIN
另外,我建议您为表使用别名而不是完整的表名。当一致使用别名时,查询变得更容易扫描和理解。拼写整个表名经常会掩盖查询的其他部分。