两个表:Department
,Employee
Department
列:
DepartmentID
,DepartmentName
Employee
列:
EmployeeID
EmployeeName
DepartmentID
现在我希望结果列DepartmentName
,EmployeeName
用于那两个表中没有任何匹配值DepartmentID
的记录。
怎么做?有多少其他方式可以做到?
答案 0 :(得分:1)
答案 1 :(得分:1)
以下查询将帮助您列出员工表中未引用的所有部门
select DepartmentName
FROM Department d
left outer join EMPLOYEE e
on e.DepartmentID = d.DepartmentID
where e.EmployeeID is null
以下查询将帮助您列出所有没有相应部门的员工
select EmployeeName
FROM EMPLOYEE e
left outer join Department d
on e.DepartmentID = d.DepartmentID
where d.DepartmentID is null
答案 2 :(得分:0)
这是一个极度延迟的答案,但我想发布它以帮助遇到此问题的其他人 - 它是理解联接的好资源。在您的情况下(或类似的),您将需要一个带有排除项的FULL OUTER JOIN(即,其中为NULL)。该链接包含您需要的图像和语法。
Here's完整的海报,以帮助了解其他联接。
Sandy的第二个链接类似,但图片更好,更容易关注我发布的来源。我本来会评论,但我的名声不够高。
答案 3 :(得分:-1)
SELECT d.DepartmentName,e.EmployeeName
FROM Department as d
FULL JOIN Employee as e
ON e.DepartmentID = d.DepartmentID
WHERE e.DepartmentID IS null OR d.DepartmentID IS null