2013-04-09 42 views
0

我有表A带有Id列。仅返回其他表中不存在值的行

我有表B与Id1和Id2列。

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

因此,如果表阿看上去像以下:

Id  
123 
456 
789 

表乙看上去像以下:

Id1 Id2  
123 545 
343 432 
184 789 

行1和3将不会被返回为它们每场比赛在表A。但是,表b中的第2行均不匹配,因此将返回。

我一直在想我的头,似乎无法弄清楚查询。任何帮助,将不胜感激!

回答

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

为什么要查询'a'两次? 'select b。* from tableB b left join tableA a on(b.id1 = a.id or b.id2 = a.id)其中coalesce(a.id1,a.id2)为空' – haki 2013-04-10 07:48:11

+0

@haki - 良好的解决方案!您可以将其作为单独的答案发布。 – 2013-04-10 08:55:54

1

当寻找其中的一些数据确实与另一个表中没有存在记录总是有存在条款,因此名称;-)

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