有两个表 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
有没有办法实现这个目标?
答案 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
答案 1 :(得分:1)
我认为你也可以不用exists
来完成这项工作 -
select * from TABLE2 where subject = 1 and NOT exists
(select 1 from TABLE1 where subject = 1 and table1.id = table2.id)