繁体   English   中英

返回列名称,其中连接条件为空

[英]Return column name where Join condition is null

我有2个表格:Employee和Person with the structure

Employee: Id, PersonId, Designation, IsActive
Person:Id, Name, Contact

员工的PersonId列引用Person的ID,可以为null

我需要返回员工的姓名,我的加入条件是

SELECT emp.Salary, emp.Designation, emp.IsActive, p.Name from Employee emp
JOIN Person P ON P.Id = emp.PersonId or (p.Id is NULL AND emp.Id IS NULL)

这是不正确的,因为我的要求是:

If emp.PersonId = null, return p.Name = NULL
else return p.Name = Person's Name from table

关于这个有什么建议吗?

你需要一个外部联接

SELECT emp.Salary, emp.Designation, emp.IsActive, p.Name 
from Employee emp
left JOIN Person P 
ON P.Id = emp.PersonId 

当您使用INNER JOIN(或JOIN)时,仅选择与联接条件匹配的行,在您的示例中,您永远不会拥有NULL Person名称,因为如果Employee未与Person关联,则不会选择该记录。

如果您使用OUTER JOIN(LEFT / RIGHT JOIN),则将从主表中选择ALL记录(第一个为LEFT,第二个为RIGHT)。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM