Oracle (+) outer join and constant values

后端 未结 4 1966
感情败类
感情败类 2021-02-09 13:13

I\'m running into an issue with which I can\'t figure out how to correctly configure a join. I\'m using reporting software that utilizes the (+) indicators in the WHERE clause f

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-09 13:39

    I'm going to explain this by using equivalent "ANSI JOIN" syntax:

    Option 1

    SELECT *
    FROM TXN
    LEFT JOIN CHK 
      ON TXN.CHK_ID = CHK.CHK_ID
    WHERE TXN.CURRENT = 'Y'
    AND CHK.CURRENT = 'Y'
    

    Option 2

    SELECT *
    FROM TXN
    LEFT JOIN CHK 
      ON TXN.CHK_ID = CHK.CHK_ID 
      AND CHK.CURRENT = 'Y'
    WHERE TXN.CURRENT = 'Y'
    

    As you can see, in option 1, your constant predicates are applied after the LEFT JOIN table expression is specified, i.e. on the result of the LEFT JOIN.

    In option 2, one of your constant predicates is part of the LEFT JOIN expression.

    How does LEFT JOIN work?

    The idea of a LEFT JOIN is that it will return all rows from the LEFT side of the JOIN expression, regardless if there is a matching row on the other side, given the join predicate. So, in option 2, regardless if you find a row in CHK with CURRENT = 'Y' for a row in TXN, the row in TXN is still returned. This is why you get more rows in option 2.

    Also, this example should explain why you should prefer the "ANSI JOIN" syntax. From a maintenance / readability perspective, it is much more clear what your query is doing.

提交回复
热议问题