【Oracle】【22】in、exists、not in、not exists

前言:

1,in 和 exists

2,not in 和 not exists

3,in 和 =

正文:

1,in 和 exists

in是把外表和内表作hash(字典集合)连接

exists是对外表作循环,每次循环再对内表进行查询

查询效率:

一直以来认为exists比in效率高的说法是不准确的,如果查询的两个表大小相当,那么用in和exists差别不大;

如果两个表中一个较小一个较大,则子查询表大的用exists,子查询表小的用in

-- 表A(小表),表B(大表)

-- 效率低,用到了A表上ID列的索引
select * from A where A.ID in(select B.ID from B);

-- 效率高,用到了B表上ID列的索引
select * from A where exists(select B.ID from B where B.ID = A.ID) 

-- 效率高,用到了B表上ID列的索引
select * from B where B.ID in(select A.ID from A) 

-- 效率低,用到了A表上id列的索引
select * from B where exists(select A.ID from A where A.ID = B.ID)

2,not in 和 not exists

not in,如果子查询中返回的任意一条记录含有空值,则查询将不返回任何记录。如果子查询字段有非空限制,则可以使用。

查询效率:

not in会对内外表都进行全表扫描,没有用到索引;而not exists的子查询依然能用到表上的索引。

所以无论哪个表大,用not exists都比not in 要快。

3,in 和 =

-- 以下两条sql是等价的
select name from employee where name in('张三','李四','王五');

select name from employee where name='张三' or name='李四' or name='王五';

参考博客:

SQL查询中in、exists、not in、not exists的用法与区别_数据库技术_Linux公社-Linux系统门户网站
https://www.linuxidc.com/Linux/2016-04/130285.htm

猜你喜欢

转载自www.cnblogs.com/huashengweilong/p/11056183.html