我目前有2个表,我正在使用INNER JOIN子句进行查询。我的第一个标记为departments的表非常简单,只包含3个字段--deptID,deptName和companyID。我的第二个标记为departmentMemberships的表更简单,只包含2个字段--deptID和employeeID。我当前的SQL语句查询这两个表并返回所有deptID,deptName和每个部门的员工数。如果上述部门中没有任何员工,我的查询将不会返回部门。这是我目前的查询。
`SELECT departments.deptID, departments.deptName,
COUNT(departmentMemberships.deptID) AS employeeCount
FROM departmentMemberships
INNER JOIN departments
ON departmentMemberships.deptID = departments.deptID
WHERE departments.companyID = 1
GROUP BY departments.deptID, departments.deptName
ORDER BY departments.deptName ASC;`
请原谅我对TSQL的经验不足,但我怎么能改变这个查询以返回所有部门,包括那些没有员工注册的部门?
非常感谢
答案 0 :(得分:5)
如上所述,请将INNER JOIN
更改为RIGHT OUTER JOIN
。但我更喜欢自己LEFT JOIN
;它更容易遵循。即:
SELECT departments.deptID
, departments.deptName
, COUNT(departmentMemberships.deptID) AS employeeCount
FROM departments
LEFT OUTER JOIN departmentMemberships
ON departmentMemberships.deptID = departments.deptID
WHERE departments.companyID = 1
GROUP BY departments.deptID, departments.deptName
ORDER BY departments.deptName ASC