一直以为IN子查询比exists子查询效率低,而连接(JOIN)最高,
今天在“高级程序员考试(指南)”看到,IN子查询的效率比连接查询效率高
---------------------------------------------------------------
不是吧,in比join高?呵呵~~~~,我也学到一招
---------------------------------------------------------------
IN子查询的效率是比连接查询效率高
不过好像exists查询效率也不高
---------------------------------------------------------------
IN子查询的效率比连接查询效率高?不会吧!
---------------------------------------------------------------
可能还要考虑到具体的语句与环境
---------------------------------------------------------------
不能简单这样说的,要看IN,exists等的()里面的语句的
---------------------------------------------------------------
当然了,exists in join 这个顺序,学校里就讲过呀,不过这是理论,exists和in我实践过,join就没比过,应该说数据量约大差别越明显。记得有一次解一道题,最后while循环+字符函数居然比join快,出忽我的意料
---------------------------------------------------------------
exists 肯定是最高的,这点不容怀疑.
我今天也专门做过测试.
select name from 表
与
if exists(select * from 表) print 'aa'
前者差不多10秒,而后一闪就出来了.
---------------------------------------------------------------
in比join高?呵呵~~~~,我也学到一招
---------------------------------------------------------------
in可以分为三类:
1、形如select * from t1 where f1 in ('a','b'),应该和select * from t1 where f1 ='a' or f1='b' 或者 select * from t1 where f1 ='a' union all select * from t1 f1='b'比较效率,搂主可能指的不是这一类,这里不做讨论。
2、形如select * from t1 where f1 in (select f1 from t2 where t2.fx='x'),其中子查询的where 里的条件不受外层查询的影响,这类查询一般情况下,自动优化会转成exist语句,也就是效率和exist一样。
3、形如select * from t1 where f1 in (select f1 from t2 where t2.fx=t1.fx),其中子查询的where 里的条件受外层查询的影响,这类查询的效率要看相关条件涉及的字段的索引情况和数据量多少,一般认为效率不如exists。
除了第一类in语句都是可以转化成exists 语句的,一般编程习惯应该是用exists而不用in.
和连接的比较情况太多,说不完
---------------------------------------------------------------
in 和 join 的可比性不大,join应该和子查询比
---------------------------------------------------------------
如A,B两个表,
当只显示一个表的数据如A,关系条件只一个如ID时,使用IN更快:
select * from A where id in (select id from B)
当只显示一个表的数据如A,关系条件不只一个如ID,col1时,使用IN就不方便了,可以使用EXISTS:
select * from A where exists (select 1 from B where id = A.id and col1 = A.col1)
当只显示两个表的数据时,使用IN,EXISTS都不合适,要使用连接:
select * from A left join B on id = A.id
所以使用何种方式,要根据要求来定。
---------------------------------------------------------------
select count(*)
from A
where exists(select id from B)
select count(*)
from A
where id in (select id from B)
这两句可不是一样的功能,当然有可能你的结果正好是一样的,因为你的A表的所有ID在表表都出现了.
---------------------------------------------------------------
select count(*)
from A
where exists(select id from B)
select count(*)
from A
where id in (select id from B)
这两句可不是一样的功能,当然有可能你的结果正好是一样的,因为你的A表的所有ID在表表都出现了.