由于本人一直使用exist,很少使用in,所以没有发现这个问题。
数据
create table t1(n1 number, v1 varchar2(20));
create table t2(n1 number, v1 varchar2(20));
insert into t1 values(99,'99');
insert into t2 values (null, '88'); --注意这里n1是null
查询
SQL> select * from t1 where n1 = 99;
N1 V1
---------- --------------------
99 99
SQL> select * from t2 where n1 = 99;
未选定行
SQL>
正常的理解是99不再表t2中,所以应该查询出来一条
SQL> select * from t1 where t1.n1 not in (select t2.n1 from t2);
未选定行
SQL>
原因在t2表中有的n1是null
正确写法如下
SQL> select *
2 from t1
3 where t1.n1 is not null
4 and t1.n1 not in (select t2.n1 from t2 where
t2.n1 is not null);
N1 V1
---------- --------------------
99 99
SQL>
本人通常习惯使用exists,sql如下
SQL> SELECT * FROM T1 WHERE NOT EXISTS (SELECT 1 FROM T2 WHERE
T1.N1 = T2.N1)
2 /
N1 V1
---------- --------------------
99 99
SQL>