I tried following query to get the missing records in 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
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). 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
.
If you want to handle this case, then you need logic in the exists
clause as well:
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;
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.