左外连接不总是匹配

时间:2018-09-21 20:06:57

标签: sql sql-server left-join

我从一个带有两个联接的SQL查询开始,我正在获取期望的确切数据。这就是当前查询。

SELECT DISTINCT o.OrganizationHierarchyUnitLevelFourCd, o.OrganizationHierarchyUnitLevelThreeNm, o.OrganizationHierarchyUnitLevelFourNm
FROM Lab_Space l
JOIN Worker w ON l.Contact_WWID = w.WWID AND w.Employee_Status_Code = 'A'
JOIN Org_Hierarchy o ON o.OrganizationHierarchyUnitLevelThreeNm IS NOT NULL AND w.Org_Hierarchy_Unit_Cd = o.OrganizationHierarchyUnitCd
ORDER BY o.OrganizationHierarchyUnitLevelThreeNm, o.OrganizationHierarchyUnitLevelFourNm

这以类似

的行结束
  

1234 |财务| IT

现在,我创建了一个新表,用于跟踪是否要在输出中包含该组织。该表只有两列,一个组织ID和一个bit字段。因此,我认为我可以LEFT OUTER JOIN,因为第二张表将没有关于所有所有组织的数据,所以我将查询扩展到了:

SELECT DISTINCT o.OrganizationHierarchyUnitLevelFourCd, o.OrganizationHierarchyUnitLevelThreeNm, o.OrganizationHierarchyUnitLevelFourNm, v.Include
FROM Lab_Space l
JOIN Worker w ON l.Contact_WWID = w.WWID AND w.Employee_Status_Code = 'A'
JOIN Org_Hierarchy o ON o.OrganizationHierarchyUnitLevelThreeNm IS NOT NULL AND w.Org_Hierarchy_Unit_Cd = o.OrganizationHierarchyUnitCd
LEFT OUTER JOIN Validation_Email_Org_Unit_Inclusion v ON o.OrganizationHierarchyUnitCd = v.OrganizationHierarchyUnitCd
ORDER BY o.OrganizationHierarchyUnitLevelThreeNm, o.OrganizationHierarchyUnitLevelFourNm

我遇到的问题是,我最终遇到这样的行:

  

1234 |财务| IT | NULL
  1234 |财务| IT | 1

由于Validation_Email_Org_Unit_Inclusion表中包含用于1234机构的1,因此,我希望只得到一个值为1的单行,而不包括具有NULL的行。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您输出了OrganizationHierarchyUnitLevelFourCd,但当前加入了OrganizationHierarchyUnitCd。在输出的同一列上联接以获取相应的值。

SELECT DISTINCT o.OrganizationHierarchyUnitLevelFourCd, ...
...
LEFT OUTER JOIN Validation_Email_Org_Unit_Inclusion v ON o.OrganizationHierarchyUnitLevelFourCd = v.OrganizationHierarchyUnitCd
...