结论
1.IN适合于外表大而内表小的情况;
2.EXISTS适合于外表小而内表大的情况
3.当主表数据与子表数据一样大时,in与exists效率差不多,可任选一个使用
区别
1.IN
select * from A
where id in(select id from B)
------------------------------------
for select id from B
for select * from A where A.id = B.id
分析:
0、当前的in子查询是B表驱动A表
1、mysql先将B表的数据一把查出来至于内存中
2、遍历B表的数据,再去查A表(每次遍历都是一次连接交互,这里会耗资源)
3、假设B有100000条记录,A有10条记录,会交互100000次数据库;再假设B有10条记录,A有100000记录,只会发生10次交互。
结论:in()适合B表比A表数据小的情况
2.EXISTS
select a.* from A a
where exists(select 1 from B b where a.id=b.id)
-----------------------------------------------
for select * from A
for select 1 from B where B.id = A.id
分析:
0、当前exists查询是A表驱动B表
1、与in不同,exists将A的纪录数查询到内存,因此A表的记录数决定了数据库的交互次数
2、假设A有10000条记录,B有10条记录,数据库交互次数为10000;假设A有10条,B有10000条,数据库交互次数为10。