带有空值的SQL自连接问题

0 sql join

让我们看一下Employee表的经典自联接示例,其中包含列empId,managerId,empName,Managername.我试图查看每个作为经理的员工,然后使用表名中的其他名称加入经理姓名.现在我遇到问题的部分是某些记录的经理ID可以为null.在这些情况下,sql不起作用,因为对于mgrId为null的行,mgr.name为null:

SELECT emp.Name, mgr.Name FROM Employee e
LEFT JOIN Employee mgr ON e.empId=mgr.mgrId 
JOIN Name nm ON nm.name = mgr.Name
Run Code Online (Sandbox Code Playgroud)

有人可以为此提供解决方案吗?

很抱歉过于简单化了问题:它更像是每个员工行,我也想要mgr行(mgrId为empId的行),然后将mgr行的属性加入到其他表中.像这样的东西:

select 
   emp.empId,mgr.empId,dept.deptName 
from Employee emp  
JOIN Address addr on 
   emp.houseNo = addr.houseNo  
JOIN dept dept on 
   dept.deptAddress = addr.deptAddress  
LEFT JOIN Employee mgr on 
   emp.empId = mgr.empId  
JOIN Address address on 
   mgr.houseNo = address.houseNo  
JOIN dept department on 
   department.houseNo=address.deptAddress  
where 
   department.deptId=dept.deptId  
Run Code Online (Sandbox Code Playgroud)

使用所有左连接对此无效.谢谢您的帮助.

Mar*_*ett 8

一旦引入左连接,您通常也希望跟随LEFT的所有后续连接.链中的单个INNER JOIN也会将所有内容减少到INNER JOIN之前.

SELECT 
    emp.Name, mgr.Name 
FROM Employee e
LEFT JOIN Employee mgr ON 
    e.empId = mgr.mgrId 
LEFT JOIN Name nm ON 
    nm.name = mgr.Name
Run Code Online (Sandbox Code Playgroud)