完全外部联接在左侧确实存在,而右侧却没有NULL值

时间:2020-03-25 11:35:59

标签: sql sql-server tsql

我必须在两个来源EmployeeODS和EmployeeDWH之间进行比较,以获取新的或已删除的记录,如下所示:

SELECT bf.EmployeeId AS EmployeeIdODS
      ,bf.FunctionId AS FunctionIdODS
      ,bf.Scope AS ScopeODS
      ,bf.Primacy AS PrimacyODS
      ,bn.EmployeeId AS EmployeeIdDWH
      ,bn.FunctionId AS FunctionIdDWH
      ,bn.Scope AS ScopeDWH
      ,bn.Primacy AS PrimacyDWH
      ,bn.BI_StartDate
      ,bn.BI_EndDate
       FROM EmployeeODS bf
FULL OUTER JOIN EmployeeDWH bn ON bf.EmployeeId = bn.EmployeeId 
AND bf.FunctionId=bn.FunctionId 
AND bf.Scope=bn.Scope
WHERE bf.EmployeeId=15366

输出如下:

EmployeeIdODS   FunctionIdODS   ScopeODS    PrimacyODS  EmployeeIdDWH   FunctionIdDWH   ScopeDWH    PrimacyDWH  BI_StartDate            BI_EndDate
15366           45              AMAGR       2           15366           45              AMAGR       2           2020-03-25              9999-12-31 
15366           940             AMATUN      1           15366           940             AMATUN      1           2020-03-25              9999-12-31 

当我从EmployeeODS删除具有FunctionIdODS = 45和ScopeODS ='AMAGR'的记录时:

DELETE FROM EmployeeODS WHERE EmployeeId=15366 AND Scope='AMAGR' AND FunctionId=45

我得到的输出是:

EmployeeIdODS   FunctionIdODS   ScopeODS    PrimacyODS  EmployeeIdDWH   FunctionIdDWH   ScopeDWH    PrimacyDWH  BI_StartDate            BI_EndDate
15366           940             AMATUN      1           15366           940             AMATUN      1           2020-03-25              9999-12-31 

我的预期输出:

EmployeeIdODS   FunctionIdODS   ScopeODS    PrimacyODS  EmployeeIdDWH   FunctionIdDWH   ScopeDWH    PrimacyDWH  BI_StartDate            BI_EndDate
NULL            NULL            NULL        NULL        15366           45              AMAGR       2           2020-03-25              9999-12-31 
15366           940             AMATUN      1           15366           940             AMATUN      1           2020-03-25              9999-12-31 

1 个答案:

答案 0 :(得分:2)

您的WHERE子句将FULL JOIN变成了一种较小的外部联接类型。

对于FULL JOIN,我建议在子查询中进行过滤:

   FROM (SELECT bf.*
         FROM EmployeeODS bf
         WHERE bf.EmployeeId = 15366
        ) FULL JOIN
        (SELECT bn.*
         FROM EmployeeDWH bn
         WHERE bn.EmployeeId = 15366
        ) bn
        ON bf.EmployeeId = bn.EmployeeId AND
           bf.FunctionId = bn.FunctionId AND
           bf.Scope = bn.Scope