sql优化:Exists、IN的取舍

来源:互联网 发布:mac模拟人生2中文 编辑:程序博客网 时间:2024/06/07 14:30

Exists定义

EXISTS用于检查子查询是否至少会返回一行数据,事实上该子查询并不会返回任何数据,而是返回值True(存在数据)或False,也就是说EXISTS指定一个子查询,检测行的存在。

初始化示例表

表T_A:

ID NAME 1 A1 2 A3 3 A3

表T_B:

ID A_ID NAME 1 1 B1 2 2 B2 3 2 B3

示例中有俩张表,T_AT_B,T_A一对多T_B关系。

用法

执行SQL

select id,name from T_A a where exists(    select * from T_B b where a.id = b.a_id)

执行结果为:

id name 1 A1 2 A2

流程分析

将Exists语句可以理解为:

 for aid in ( select id,name from T_A a)    loop       if ( exists ( select * from T_B b where b.a_id= a.id )       then           OUTPUT THE RECORD!       end if    end loop

具体执行顺序如下:

tep1 ==>

select id,name from T_A a where EXISTS (select * from T_B b where b.a_id=1)

Exists有值返回为true,查询结果为id =1 name=A1的行;

tep ==>

select id,name from T_A a where EXISTS (select * from T_B b where b.a_id=2)

Exists有值返回为true,返回 id =2 name=A2的行;

tep ==>

select id,name from T_A a where EXISTS (select * from T_B b where b.a_id=3)

Exists未查询到返为false,无值返回。

从分析语句可以看出,Exists全程扫描外表(此处的T_A表).

至于IN的用法与解析,与Exists类似,只是IN扫描的是内表。

结论

如果外表小,采用Exists语句速度更快。
如果内表小,采用IN语句速度更快。

也就是说EXISTS适合于外表小而内表大的情况;IN适合于外表大而内表小的情况。

另外not exists比not in速度快(not in 俩张表都会扫描)。

原创粉丝点击