简体   繁体   中英

Left Outer Join of Same Table (self-join; not first table) Not Returning Null Values

My LEFT OUTER JOIN clause on a table (not the first table) on itself (self-join too) is not returning null values, which skews my SELECT statements. The query is written (table names inconsequential):

Select
SUM(CASE WHEN table2.date =‘day’ and table4.columnX =‘5’ then table3.value1 END),
SUM(CASE WHEN table2.date=’day’ and table4.columnX IS NULL then table3.value2 END)
FROM table1
INNER JOIN table2 on ...
INNER JOIN table3 on ...
LEFT OUTER JOIN table4 on table4.columnX=’5’

In which the first SUM(CASE WHEN) statement uses on one value in table4.columnX - when it is equal to '5' - and the second SUM(CASE WHEN) statement uses all other values - whenever it is not equal to '5'.

As it stands, the query is only returning results where table4.columnX='5', and not where table4.columnX is equal to everything else. As such, it appears the LEFT OUTER JOIN is not returning all null values for table4.columnX<>'5'. I think this may be because the join is written incorrectly. As a note, there are no fields in table4 that can be joined to fields in other tables, so it has to be a self-join of some sort (I believe). Help is appreciated - thank you!

What a LEFT OUTER JOIN will do is take all the rows from the "left table" and conditionally join rows from the "right table". If for a specific row in the "left table", there is no matching row in the "right table", then your "right data values" for the joined row will be NULL.

Your join condition is strange, though, since it doesn't reference another table. If that's really what you want, then you should change it to a CROSS JOIN:

Old: LEFT OUTER JOIN table4 on table4.columnX='5'
New: CROSS JOIN table4 on table4.columnX='5'

This will join all rows in table4 where columnX = 5 to each row in your preceding query above. Not sure if that's what you're looking for...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM