简体   繁体   English

相同表的左外连接(自连接;不是第一个表)不返回空值

[英]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. 我自己的表(也不是第一个表)(同样是自联接)上的LEFT OUTER JOIN子句也不返回空值,这使我的SELECT语句产生了偏差。 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'. 其中第一个SUM(CASE WHEN)语句使用table4.columnX中的一个值-当它等于'5'时-第二个SUM(CASE WHEN)语句使用所有其他值-每当它不等于'5时'。

As it stands, the query is only returning results where table4.columnX='5', and not where table4.columnX is equal to everything else. 就目前而言,查询仅返回table4.columnX ='5'的结果,而不返回table4.columnX等于其他所有结果的结果。 As such, it appears the LEFT OUTER JOIN is not returning all null values for table4.columnX<>'5'. 这样,看来LEFT OUTER JOIN没有返回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). 需要注意的是,table4中没有可与其他表中的字段连接的字段,因此它必须是某种自连接(我相信)。 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". LEFT OUTER JOIN将要做的是取走“左表”中的所有行,并有条件地LEFT OUTER JOIN “右表”中的行。 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. 如果对于“左表”中的特定行,“右表”中没有匹配的行,则联接行的“右数据值”将为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: 如果这确实是您想要的,则应将其更改为CROSS JOIN:

Old: LEFT OUTER JOIN table4 on table4.columnX='5' 旧: LEFT OUTER JOIN table4 on table4.columnX='5'
New: CROSS JOIN table4 on table4.columnX='5' 新增内容: 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. 这会将table4columnX = 5的所有行连接到上述先前查询中的每一行。 Not sure if that's what you're looking for... 不知道这就是您要找的东西吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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