码迷,mamicode.com
首页 > 其他好文 > 详细

in和exists的使用

时间:2018-06-21 01:31:20      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:.com   笛卡尔积   情况下   tab   sele   完全   table   bsp   href   

两者执行流程完全不一样。

in的过程

select * from tableA a where a.id in (select b.a_id from tableB b);
 
1)首先子查询,查询B表中所有的aid,结果集 listB。
2)进行外查询,结果集 listA。
3)list和listB取笛卡尔积,即有 listA.len*listB.len 条记录。根据 a.id=b.a_id 对笛卡尔积结果进行筛选。
for(t in listA.len*listB.len){
  if(t.id == t.aid) {
    list.add(t);
  }
}
retrun list;
 
所以,in的效率取决于in子查询。

exists的过程

select * from tableA a where exists (select 1 from tableB b where a.id=b.a_id);
 
1)外查询,这里是select * from tableA a,结果集 listA。
2)对 listA 的a.id进行exists筛选。
for(a in listA.length){
  if( (select 1 from tableB b where b.a_id=a.id) != null ) {
    list.add(a);
  }
}
 
所以,exists的效率取决于外查询。

总结

exist不一定比in高效。要根据外查询和子查询的情况而定。
如果外查询表较大且有索引,而子查询的结果集比较小时,使用in效率高;
相反的,如果外查询的结果集较小,子查询表较大且有索引时,使用exists好。--没有索引也一样。
当外表和查询子表情况差不多时,两者差不多的,当然exists应该更好,没有笛卡尔积。

not in 和 not exists

虽然“一般情况下,使用exists比使用in更好”的说法不准确,
但是“一般情况下,使用 not exists 比使用 not in 更好”的说法是没问题的。
使用 not in 会对外表和内表进行全表扫描,这回忽略掉索引;使用not exists的子查询可以使用表的索引的。
所以,无论哪个表大,使用 not exists 要比 not in 来的快。

 参考

in和exists的使用

标签:.com   笛卡尔积   情况下   tab   sele   完全   table   bsp   href   

原文地址:https://www.cnblogs.com/noodlerkun/p/9206726.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!