仅返回其他表中不存在值的行

时间:2013-04-09 17:58:19

标签: plsql

我的表A 带有Id列。

我的表B 带有Id1和Id2列。

我想返回表格b 中的所有行,表格A 中的Id1或Id2都不存在。如果表格b 中的Id1或Id2在表格A 中匹配,我想返回该结果。

因此,如果表格A 如下所示:

Id    
123
456
789

表格B 如下所示:

Id1 Id2    
123 545
343 432
184 789

第1行和第3行不会返回,因为它们在表A 中都匹配。但是,表b 中的第2行在两列上都不匹配,因此会返回。

我一直在绞尽脑汁,似乎无法弄清楚查询。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

假设您的Id列不为空:

select * from tableB 
where Id1 not in (select Id from tableA) 
and Id2 not in (select Id from tableA) 

select b.* 
from tableB b
left join tableA a1 on b.id1=a1.id
left join tableA a2 on b.id2=a2.id
where a1.id is null and a2.id is null

答案 1 :(得分:1)

当在另一个表中查找某些数据不存在的记录时,总会有 exists 子句,因此名称; - )

select * from tableB 
where not exists
(
  select *
  from tableA
  where id in (tableB.id1, tableB.id2)
); 
相关问题