官方文档:

Home / Database / Oracle Database Online Documentation 11g Release 2 (11.2) / Database Administration
EXISTS Condition
An EXISTS condition tests for existence of rows in a subquery.
EXISTS条件测试子查询中是否存在行。
exists (sql 返回结果集为真)
not exists (sql 不返回结果集为真)

实验:

create table scott.a (id number(10),name varchar(32));

insert into scott.a
select 1,'A1' from dual
union all
select 2,'A2' from dual
union all
select 3,'A3' from dual;
commit;

create table scott.b(id number(10),aid number(10),name varchar2(32));

insert into scott.b
    select 1,1,'B1' from dual
    union all
    select 2,2,'B2' from dual
    union all
    select 3,2,'B3' from dual;
    commit;

SCOTT@PROD>select * from scott.a;
        ID NAME
---------- --------------------------------
         1 A1
         2 A2
         3 A3

SCOTT@PROD>select * from scott.b;
        ID        AID NAME
---------- ---------- --------------------------------
         1          1 B1
         2          2 B2
         3          2 B3

表A与表B是1:B关系,怎么看呢?

只需要对两表关联列进行汇总统计就能知道两表是什么关系:把关联列进行汇总再 order by 一下

SCOTT@PROD>select id,count(*) from scott.a group by id order by count(*) desc;
        ID   COUNT(*)
---------- ----------
         1          1
         3          1
         2          1
SCOTT@PROD>select aid,count(*) from scott.b group by aid order by count(*) desc;
       AID   COUNT(*)
---------- ----------
         2          2
         1          1

B表的count(*)的值大于1,属于N:1关系,看count(*)的值,都是1  就是1:1关系,count(*)有大于1的就是1:N关系

emp:dept N:1 返回N的关系,不会返回1的关系

查看等价改写:

SCOTT@PROD>select id,name from scott.a where id in (select aid from scott.b);

        ID NAME
---------- --------------------------------
         1 A1
         2 A2

关联列是a.id = b.aid

以上查询使用了in语句,in()只执行一次,它查出B表中的所有id字段并缓存起来.之后,检查A表的id是否与B表中的id相等,如果相等则将A表的记录加入结果集中,直到遍历完A表的所有记录.

可以看出,当B表数据较大时不适合使用in(),因为它会B表数据全部遍历一次.

等价改写:

select id,name from scott.a exists (select 1 from scott.b where a.id=b.aid);

以上查询使用了exists语句,exists()会执行A.length次,它并不缓存exists()结果集,因为exists()结果集的内容并不重要,重要的是结果集中是否有记录,如果有则返回true,没有则返回false.

结论:exists()适合B表比A表数据大的情况

当A表数据与B表数据一样大时,in与exists效率差不多,可任选一个使用.