in 和exists
对于以上两种查询条件,in是把外表和内表作hash 连接,而exists 是对外表作loop 循环,每次loop 循环再对内表进行查询。
一直以来认为exists 比in 效率高的说法是不准确的。在不同的情况下,exists与in的性能各有优缺项,如果查询的两个表大小相当,那么用in 和exists 差别不大。
下面以实例来进行说明:
select * from A where id in(select id from B);
select * from A where exists (select 1 from B where A.id = B.id);
1、in的应用原理
在select * from A where id in(select id from B); 中,in()中的子查询只执行一次,它查询出B表中的所有ID值并缓存起来;之后,在内存中检查A表的id是否与B表中的id值相等,如果相等则则将A表的记录加入到结果集中,直到遍历完A表中的所有记录。
它查询的过程类似于一下过程
Array A={select * from A};
Array B={select id from B};
for (int i=0;i<A.length;i++){
for (int j=0;j<B.length;j++){
if (A[i].id == B[j].id){
resultSet.add(A[i]);
break;
}
}
}
如:A表有10000条记录,B表有10000