EXISTS的使用详解

1.exists的使用场合:
    exists 用于只能用于子查询,可以替代in,若匹配到结果,则退出内部
查询,并将条件标志为true,传回全部结果资料,in 不管匹配到匹配不到都
全部匹配完毕,使用exists 可以将子查询结果定为常量,不影响查询效果,
而且效率高.

2.in和exists对比:
    若子查询结果集比较小,优先使用in,若外层查询比子查询小,优先使
用exists。因为若用in,则oracle 会优先查询子查询,然后匹配外层查询,
若使用exists,则oracle 会优先查询外层表,然后再与内层表匹配。最优化
匹配原则,拿最小记录匹配大记录.

3.not exists的使用
与exists 含义相反,也在子查询中使用,取出不满足条件的,与not in有一
定的区别,注意有时候not exists不能完全替代not in.

not exists和not in不同的情况:

drop table test1;
drop table test2;
create table test1(a number,b number);
create table test2(a number,b number);
insert into test1 values(1,1);
insert into test1 values(1,2);
insert into test2 values(1,1);
insert into test2 values(1,null);
--使用not exists找出test1不在test2中的记录,都用b字段匹配 --返回结果1,2 select * from test1 t1 where not exists (select 1 from test2 t2 where t1.b=t2.b); --使用not in,没有结果返回,因为test2中的b有null select * from test1 t1 where t1.b not in (select t2.b from test2 t2); --用相关子查询,结果同not exists select * from test1 t1 where t1.b not in (select t2.b from test2 t2 where t1.b=t2.b);

 

posted @ 2017-12-08 01:02  碧水幽幽泉  阅读(1669)  评论(0编辑  收藏  举报