« 上一篇 | 下一篇»

关于 not in 与not exists 的一个区别

songhefei | 08 05, 2006, 22:04 | oracle 数据库 | (255 Reads)

SQL> create table a (a number);

SQL> insert into a values (1);

SQL> insert into a values (2);

SQL> create table b (a number );

SQL> insert into b values (1);

SQL> select * from a where a.a not in (select a from b);   

     A

   -----

     2

SQL> select * from a where not exists (select 1 from b where b.a=a.a);

     A

   -----

     2

这个时候是有什么区别的.

 

SQL> insert into b values(null);

SQL> commit ;

SQL> select * from a where a.a not in (select a from b);   

    no rows selected;

SQL> select * from a where not exists (select 1 from b where b.a=a.a);

     A

   -----

     2

我们发现当NOT IN subquery 中存在null 的情况下,会返回空行,所以我们再写SQL not in subquery 的时候,要加入 where a is not null;

在oracle CBO中,not exists 与 not in 都是优化器都是选择anti_join的连接方式.


Trackback URL: http://blog.itpub.net//trackback.php?id=86651
Comments