使用NOT IN的多个SELECT - 内部Select语句返回空,整个SELECT返回空

时间:2013-05-20 20:15:00

标签: sql oracle select multiple-select

有两个表 TABLE1 TABLE2 ,其中有一个公共字段 ID 。我想根据 ID 值从 TABLE1 中检索 TABLE2 中的值。

select * from TABLE2 where subject = 1 and ID NOT IN (select ID from TABLE1 where subject = 1)

示例:

  

表1
ID主题
1 1

     

表2
ID主题
1 1
2 1

预期结果为2,工作正常。

但是当 TABLE1为空内部 select ID from TABLE1 where subject = 1返回空时,整个select语句返回空。 但预期结果为1,2

有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:3)

使用left join

select t2.* 
from table2 t2
left outer join table1 t1 on t1.id = t2.id and t1.subject = 1
where t2.subject = 1
and t1.id is null

查看good explanation of joins

答案 1 :(得分:1)

我认为你也可以不用exists来完成这项工作 -

select * from TABLE2 where subject = 1 and NOT exists
(select 1 from TABLE1 where subject = 1 and table1.id = table2.id)
相关问题