IN、EXIST
1.IN( 内外表做hash链接)
select * from A where id in (select id from B);//先执行in()并将查询数据放入缓存、再执行主表A查询
同:
List resultSet=[];
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;
}
}
}
loop_count:A.length*B.length
2.EXIST(对外表做loop循环,每次loop循环都对内部进行查询)
select a.* from A a where exists(select 1 from B b where a.id=b.id)//先执行主表A查询、再执行exists() 有记录返回true否则false
同:
List resultSet=[];
Array A=(select * from A)
for(int i=0;i<A.length;i++) {
if(exists(A[i].id) { //执行select 1 from B b where b.id=a.id是否有记录返回true 、 false
resultSet.add(A[i]);
}
}
loop_count:A.length
3.IN 、EXISTS效率
eg1:A表有10000条记录,B表有1000000条记录, in():A.length*B.length=10000*1000000 exists():A.length=10000
eg2:A表有10000条记录,B表有100000000条记录,in():A.length*B.length=10000*100000000 exists():A.length=10000
看上去无论怎样都是exists()效率比in()高、但是别忘了in()的查询数据都暂存在缓存中,而exists()却要查询数据库,相比而言内存的查询要比数据库快的多
eg3:A表有10000条记录,B表有100条记录,那么exists()还是执行10000次,还不如使用in()遍历10000*100次
一般情况下: 如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in

浙公网安备 33010602011771号