“NOT IN”与“NULL”的邂逅
今天处理了一个因“NOT IN”与“NULL”邂逅导致的问题,值得思考和总结,记录在此,供参考。(感谢John抛出的问题)
我们以实验的形式先再现一下这个问题,然后对其分析,最后给出几种解决方案。
1.创建实验表T,并分别初始化三条数据,注意T2表中包含一条空(NULL)数据。 sec@ora10g> insert into t1 values (1);
sec@ora10g> insert into t1 values (2);
sec@ora10g> insert into t1 values (3);
sec@ora10g> insert into t2 values (1);
sec@ora10g> insert into t2 values (null);
sec@ora10g> insert into t2 values (3);
sec@ora10g> commit;
2.确认T1表和T2表的数据内容
sec@ora10g> select * from t1;
X
----------
1
2
3
sec@ora10g> select * from t2;
X
----------
1
3
3.再现问题
尝试使用“NOT IN”方法获得不在T2表中出现的T1表数据。
sec@ora10g> select * from t1 where x not in (select x from t2);
no rows selected
问题已重现,明明T1中的数据“2”在T2表中没有,为什么没有返回结果呢?
原因:当子查询返回含有“NULL”记录时,使用NOT IN时将不会有返回记录。
解析:可以这么理解这个现象:Oracle中的NULL是一个不确定的状态。以T1表中的记录“2”为例,在与T2表中的NULL进行比较时,NULL既可以是“2”,也可以不是“2”,因为判断不了他们的关系,所以只能返回空记录,此乃无奈之举。
这里主要分析组合列 NOT IN 非相关子查询中 NULL 的问题。对于单列,如果 NOT IN 非相关 子查询中有 NULL,则没有结果,可以使用 NOT IN 相关子查询、NOT ...
(1,null); select * from t1 where c2 not in (select c2 from t2); no rows found select * from t1 where not exists (select 1 from t2 where...
(1,null); select * from t1 where c2 not in (select c2 from t2); no rows found select * from t1 where not exists (select 1 from t2 where...
(1,null); select * from t1 where c2 not in (select c2 from t2); no rows found select * from t1 where not exists (select 1 from t2 where...
连接代替not in_计算机软件及应用_IT/计算机_专业资料。用连接代替not in ...(+)=B.mobile and A.mobile is null 等价于 select B.mobile from A ...
Oracle 中 in 和 notin 的巨大区别在很多软件系统中,系统的性能很大程度上由数据库的性能决定。以前也曾 经做过很多次关于性能方面的各种测试,特别是关于 oracle...
SQL 里的 EXISTS与in、not exists与not in_日语学习_外语学习_教育专区。SQL...select * from t1 where exists ( select null from t2 where y = x ) ...
SQL 中 IN,NOT IN,EXISTS,NOT EXISTS 的用法和差别: IN:确定给定的值是否与子查询或列表中的值相匹配。 IN 关键字使您得以选择与列表中的任意一个值匹配的...
用LEFT JOIN 代替 NOT IN 或 NOT EXISTS: SQL> conn scott/tiger Connected....用左连接,结果 testb 表里 TempColum 的值为 NULL: SQL> SELECT a.*,b.id...
NOT IN ( select deptno from emp where deptno is not null) and deptno is not null; Explained SQL> select * from table(dbms_xplan.display); PLAN_...
热门文档