近段时间需要对数据库进行性能优化。查看网上的相关资料和评论,发现对exists和in效率上的讨论真是众说纷纭。于是决定自己进行一番测试。
在本地数据库服务器中有两个表:A(2百万数据),B(1百7十万数据);两个表通过一个custno进行关联。
下面是外表大内表小的查询语句:
select 1 from A where custno in ( select custno from B ) 耗时5秒
select 1 from A where exists ( select 1 from B where custno = A.custno ) 耗时11秒
下面是外表小内表大的查询语句:
select 1 from B where custno in ( select custno from A ) 耗时9秒
select 1 from B where exists ( select 1 from A where custno = B.custno ) 耗时9秒
从上面的结果来看,in比较适用于外表大内表小的情况;至于外表小内表大的情况就不明显。