in、not in、exists、not exists

本文总结了在使用SQL进行数据查询时的一些技巧,特别是针对in、exists、not in和not exists等关键字的不同应用场景进行了详细说明,包括如何根据表的大小选择合适的查询方式以提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

就效率上自己做了一下总结:

1、用in 或者 exists时

     如果子询的表比较大时,用exists效率要高,反之用in效率高,当主表和子表大小相当时,两者效率也同。加为in 是对主表和子表做的hashjoin,exists是对主表进行loop。如:A(大表) 、B(小表),下面写出两个效率高的查询语句(要查询两个表中id相同的数据)

    select * from A where A.id in(select id from B where id = A.id);

    select*    from B where exists(select 1 from A where id = B.id);

 

2、用not in 或者 not exists时,无论主表和子表哪个大,not in 效率都是比较低的,宁可选择minus

 

select * from A where id in(select B.id from B minus select A.id from A)

在oracle10g后,好像not exists的效率要比 minus 高