in和exists执行时,in是先执行子查询中的查询,然后再执行主查询.而exists查询它是先执行主查询,即外层表的查询,然后再执行子查询. exists 和 in 在执行时效率单从执行时间来说差不多,exists要稍微优于in.在使用时一般应该是用exists而不用in 如果子查询得出的结果集记录较少,主查询中的表较大且又有索引时应该用in,反之如果外层的主查询记录较少,子查询中的表大,又有索引时使用exists.IN时不对NULL进行处理. not exists 和 not in 比较时,…
in 是把外表和内表作hash 连接,而exists是对外表作loop循环,每次loop循环再对内表进行查询. not exists:做NL,对子查询先查,有个虚表,有确定值,所以就算子查询有NULL最终也有值返回 not in:做hash,对子查询表建立内存数组,用外表匹配,那子查询要是有NULL那外表没的匹配最终无值返回. 一直以来认为exists比in效率高的说法是不准确的. 如果查询的两个表大小相当,那么用in和exists差别不大. 如果两个表中一个较小,一个是大表,则子…
select a.col1,a.col2 from temp1 a where not exists (select 'X' from temp2 b where b.col2 = a.col1);select 'X' 可以理解成存在(exists)不存在(not exists)的含义.如上面 找到a表中 col1的字段值不与b表中col2字段值相等的数据从效率来看:1) select * from T1 where exists(select 1 from T2 where T1.a=T…
原文:mysql not in.left join.IS NULL.NOT EXISTS 效率问题记录 mysql not in.left join.IS NULL.NOT EXISTS 效率问题记录,需要的朋友可以参考下. NOT IN.JOIN.IS NULL.NOT EXISTS效率对比 语句一:select count(*) from A where A.a not in (select a from B) 语句二:select count(*) from A left join B o…
select * from A where id in (select id from B); select * from A where exists (select 1 from B where A.id=B.id); 对于以上两种情况,in是在内存里遍历比较,而exists需要查询数据库,所以当B表数据量较大时,exists效率优于in. 1.select * from A where id in (select id from B); in()只执行一次,它查出B表中的所有id字段并缓存…