简体   繁体   English

LEFT / RIGHT JOIN中的子查询过滤器

[英]Sub query filter in LEFT/RIGHT JOIN

I tried following query to get the missing records in TAB1 我尝试了以下查询以获取TAB1中的丢失记录

SELECT *
FROM TAB1 T1 
RIGHT JOIN TAB2 T2 ON T1.MemNo = T2.MemID
WHERE EXISTS ( SELECT 1
               FROM TAB3 x 
               WHERE x.Col2 =  T2.SVID
               AND x.Col1 = T1.SID )
AND T1.MemNo IS NULL

But it doesn't give any results 但这没有任何结果

Sample data; 样本数据;

TAB1

MemNo   SID

116537  S110
116537  D011
575777  D012
214438  S110
434611  D114
214438  D011
208368  D012
208368  S110

TAB2

MemID   SVID

116537  110
116537  11
214438  11
434675  114
214438  110
575788  12
208368  12
208368  110


TAB3

Col1    Col2

D011    11
S110    110
D114    114
D012    12

How should I change the query to get the expected results. 我应该如何更改查询以获得预期的结果。 Which is mentioned as below 如下所述

TAB2

MemID   SVID

575788  12
434675  114

In case of INNER JOIN this works fine 在INNER JOIN的情况下可以正常工作

Thanks 谢谢

Here is your query, written so I understand it better: 这是您写的查询,以便我更好地理解:

select *
from tab2 t2 left outer join
     tab1 t1
     on t1.MemNo = t2.MemId
where exists (SELECT 1
              FROM TAB3 x 
              WHERE x.Col2 =  T2.SVID AND x.Col1 = T1.SID ) and
      T1.MemNo IS NULL

The column t1.MemNo is NULL only when the outer join fails to find a match in that table (because it is part of the join condition). 仅当外部t1.MemNo未能在该表中找到匹配项时(因为它是t1.MemNo条件的一部分),列t1.MemNo为NULL。 When this is NULL then so is T1.SID , so the exists clause will find no rows because one of the AND conditions evaluates to NULL . 当这是NULL那么这样是T1.SID ,所以exists子句将找不到行因为一个AND条件计算为NULL

If you want to handle this case, then you need logic in the exists clause as well: 如果要处理这种情况,那么还需要在exists子句中提供逻辑:

select *
from tab2 t2 left outer join
     tab1 t1
     on t1.MemNo = t2.MemId
where exists (SELECT 1
              FROM TAB3 x 
              WHERE x.Col2 =  T2.SVID AND (x.Col1 = T1.SID or t1.SID is null)) and
      T1.MemNo IS NULL;

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

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