oracle的in和exists区别以及多条件的in的改写

in和exists的区别

实际上in和exists是有应用环境的,当数据量相差不大时,区别不大,效率和数据本身分布状态有关。
当tableA>>tableB用in

select * from tableA a where a.col in(select b.col from tableB b)


当tableA<<tableB用exists

select * from tableA a where exists (select * from tableB b where a.col=b.col)


原因在于in会查出所有in括起来的子句结果并缓存,而exists不会取其子句的所有数据一旦符合条件会马上返回。(大概?需要求证)

参见:sql优化--in和exists效率

多条件的in的改写

下面的语句oracle会报错

select * from tableA a where a.col1,a.col2 in(select b.col1,b.col2 from tableB b)

应当对where后面的字段加括号where (a.col1,a.col2)或者用exists改写

--in子句
select * from tableA a where (a.col1,a.col2) in(select b.col1,b.col2 from tableB b)
--exists子句
select * from tableA a where exists (select * from tableB b where a.col1=b.col1 and a.col2=b.col2)

猜你喜欢

转载自blog.csdn.net/programerbismark/article/details/81875894
今日推荐