Oracle中的EXISTS与IN我看到有的帖子上说Oracle SQL中尽量用EXISTS代替IN,但我后来看应该准确讲是:对于带有子表查询的情况,使用EXISTS效率要高于IN,但如果仅仅是字段选择,例如:select * from table whe

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/02 18:51:56
Oracle中的EXISTS与IN我看到有的帖子上说Oracle SQL中尽量用EXISTS代替IN,但我后来看应该准确讲是:对于带有子表查询的情况,使用EXISTS效率要高于IN,但如果仅仅是字段选择,例如:select * from table whe

Oracle中的EXISTS与IN我看到有的帖子上说Oracle SQL中尽量用EXISTS代替IN,但我后来看应该准确讲是:对于带有子表查询的情况,使用EXISTS效率要高于IN,但如果仅仅是字段选择,例如:select * from table whe
Oracle中的EXISTS与IN
我看到有的帖子上说Oracle SQL中尽量用EXISTS代替IN,但我后来看应该准确讲是:
对于带有子表查询的情况,使用EXISTS效率要高于IN,但如果仅仅是字段选择,例如:
select * from table where num in (1,2,3);是比select * from table where num=1 or num=2 or num=3;效率高,是这样么?
但为什么我使用select * from table where num in (1,2,3);要比select * from table where num=1 or num=2 or num=3;稍慢呢?只是碰巧?好像in会自动转换为or操作,是这样的?

Oracle中的EXISTS与IN我看到有的帖子上说Oracle SQL中尽量用EXISTS代替IN,但我后来看应该准确讲是:对于带有子表查询的情况,使用EXISTS效率要高于IN,但如果仅仅是字段选择,例如:select * from table whe
in和exist的主要区别体现在对sql执行计划的影响上.
传统上认为,如果子查询的条件更具选择性(selective),就用in;而如果父查询(外层查询)的条件更具选择性(selective),就用exist.
具体的内容可以参考以下oracle原厂的手册,不好意思,oracle的原厂手册都是英文版的.
对于你举的那个例子,用in和用or是一样的,因为它们的执行计划肯定是一样的.
另外需要特别注意的是,in和exist的区别只在10.2.0.3及以前的版本中存在;而10.2.0.4及以后的版本中,in和exist的效果是完全一样的,手册中也删除了有关二者区别的说明.
以下是对手册的引用:
In certain circumstances,it is better to use IN rather than EXISTS.In general,if the selective predicate is in the subquery,then use IN.If the selective predicate is in the parent query,then use EXISTS.
Sometimes,Oracle can rewrite a subquery when used with an IN clause to take advantage of selectivity specified in the subquery.This is most beneficial when the most selective filter appears in the subquery and there are indexes on the join columns.Conversely,using EXISTS is beneficial when the most selective filter is in the parent query.This allows the selective predicates in the parent query to be applied before filtering the rows against the EXISTS criteria.
补充:
看sql语句看执行计划就可以了,没必要比较某次的时间长短,因为语句执行时间长短跟很多其他因素有关,比如数据是否在buffer cache中(第二次执行一般会比第一次快不少)、数据库负载不同等.对于常量,in的效果完全等同于or,这是毫无疑问的.