left join turns into inner join

后端 未结 8 781
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 06:24
SELECT
a.foo
b.bar
c.foobar
FROM tableOne AS a
INNER JOIN tableTwo AS b ON a.pk = b.fk
LEFT JOIN tableThree AS c ON b.pk = c.fk
WHERE a.foo = \'something\'
AND c.foo         


        
8条回答
  •  执念已碎
    2020-11-29 07:05

    A Left Join returns everything from the left table (tableTwo in your example) and any matching rows from the table on the right (tableThree in your example). When you filter on something on the right side of the left join (i.e. tableThree) and you do not account for non-matching values you are effectively requiring that a value exist and that the value be 'something' which is the equivalent of an inner join. If what you are trying to do is to find all tableTwo rows which do not have a row in tableThree with a foobar value of 'something', you can move the filtering into the on clause:

    Select a.foo, b.bar, c.foobar
    From tableOne As a
        Inner Join tableTwo as b
            On b.fk = a.pk
        Left Join tableThree as c
            On c.fk = b.pk
                And c.foobar = 'something'
    Where a.foo = 'something'
        And c.pk Is Null
    

    The final addition, c.pk Is Null filters for values that do not have a tableThree value with a foobar value of 'something'.If just want to see tableThree values when they have a foobar value of 'something' (and nulls otherwise), then remove the additional filter I added of c.pk Is Null.

提交回复
热议问题