简体   繁体   中英

Excluding Certain Matching Rows in an SQL Join

My issue somewhat complex, so I will explain using simplified versions of my tables.

This is Table 1:

Value L  AID      OID
A        1         1
B        2         1
C        3         1
D        4         1
E        2         1
F        2         2
G        2         3
H        2         4

This is Table 2:

Value R  AID    OID    VAR
Z        0      1      0
Y        1      1      1
X        2      1      1
W        4      1      1
V        0      2      0
U        1      2      1
T        3      2      1

I would like to join these tables such that any row in Table 1 that doesn't have a corresponding row in Table 2 with both matching AID and OID is returned in a join to the row with a matching OID and an AID and VAR of 0. In this example it would look like this:

Value L   Value R   AID   OID   VAR
C         Z         3     1     0
F         V         2     2     0
H         V         4     2     0

I am not certain how to tackle this. Specifically, not sure how to stop the rows that have a matching AID and OID from showing up in my join, and only having the rows that don't have that match. Any advice would be appreciated.

I think you want not exists :

select t1.*
from table1 t1
where not exists (select 1
                  from table2 t2
                  where t2.aid = t1.aid and t2.oid = t1.oid and t2.var = 0
                 );

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