我的OUTER JOIN查询的WHERE子句有什么问题?

时间:2014-07-02 22:49:49

标签: sql azure-sql-database

我正在加入桌子:OLD和NEW

表:OLD

Employee_Name   Status
Ann             Y
Bob             Y
Carol   
Doug            Y
Ellen   
Frank

表:新

Employee_Name   Status
Ann             Y
Bob 
Carol   
Ellen   
Frank   

我可以通过此连接获得我想要的输出:

SELECT Old.Employee_Name AS [OldName]
  ,New.Employee_Name AS [NewName]
  ,Old.Status AS [OldStatus]
  ,New.Status AS [NewStatus]
FROM Old
   FULL OUTER JOIN New ON Old.Employee_Name = New.Employee_Name

这是:

OldName         NewName         OldStatus   NewStatus
Ann             Ann             Y           Y
Bob             Bob             Y   
Carol           Carol       
Doug                            Y   
Ellen           Ellen       
Frank           Frank   

现在我想在查询中添加一个过滤器,以便它只保留新旧状态不同的行。

如果我尝试:

SELECT Old.Employee_Name AS [OldName]
  ,New.Employee_Name AS [NewName]
  ,Old.Status AS [OldStatus]
  ,New.Status AS [NewStatus]
FROM Old
   FULL OUTER JOIN New ON Old.Employee_Name = New.Employee_Name
WHERE Old.Status <> New.Status

......它没有给出正确的输出。

对于这个例子,我认为它会给出输出:

OldName         NewName         NewStatus   OldStatus
Bob             Bob             Y   

......并且未能与Doug一起回归。

2 个答案:

答案 0 :(得分:1)

执行外部联接时,不匹配的行具有NULL个值。这就是您将条件从on子句移动到where子句的原因:

SELECT Old.Employee_Name AS [OldName],
       New.Employee_Name AS [NewName],
       Old.Status AS [OldStatus],
       New.Status AS [NewStatus]
FROM Old FULL OUTER JOIN
     New
     ON Old.Employee_Name = New.Employee_Name AND
        Old.Status <> New.Status;

答案 1 :(得分:0)

如果SQL语句中的任一运算符为null,则该行将返回null(无行)。例如,如果a <> b a = 1b = null a,则它始终不返回任何行,即使bWHERE COALESCE(Old.Status, '') <> COALESCE(New.Status, '') 不相等。< / p>

您需要将查询更改为以下内容:

{{1}}