【问题标题】:Display All Records in SQL Server Query, while Conditionally Excluding Joined Records显示 SQL Server 查询中的所有记录,同时有条件地排除连接记录
【发布时间】:2018-12-26 18:52:49
【问题描述】:

在左外连接中,如何始终确保获取左表中的所有记录(当不存在匹配项时,右表中的值为空),并且能够有条件地从右表(例如仅当右表“活动”列设置为 1 或匹配不存在时才加入)。当我有条件地从右表中排除记录时,它也会从我的左表中排除连接的记录。

我的查询示例:

SELECT people.personID, people.name, documents.documentID, documents.score FROM people 
LEFT OUTER JOIN documents ON people.personID = documents.personID 
WHERE (documents.active = 1 OR documents.active IS NULL)

这将显示我所有的人员记录,除非只有一个匹配文档的“活动”列值为 0,在这种情况下,当我希望它仍然显示时,它会排除该匹配的整个人员记录人员记录,但在活动设置为 0 时将匹配的文档记录设置为空。最好避免使用“CASE WHEN”类型的语言,但如果这是唯一的方法,我会这样做。

【问题讨论】:

    标签: sql database conditional left-join


    【解决方案1】:

    您可以在join语句中为文档设置条件:

    SELECT people.personID, people.name, documents.documentID, documents.score 
    FROM people 
    LEFT OUTER JOIN documents ON people.personID = documents.personID AND documents.active = 1 
    

    或者过滤器是子查询:

    SELECT people.personID, people.name, documents.documentID, documents.score 
    FROM people 
    LEFT OUTER JOIN 
        (SELECT * FROM documents WHERE documents.active = 1) AS documents 
    ON people.personID = documents.personID
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2012-03-26
      • 1970-01-01
      相关资源
      最近更新 更多