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

前言:linux

1,in 和 existssql

2,not in 和 not exists数据库

3,in 和 =网站

正文:spa

1,in 和 existscode

in是把外表和内表做hash(字典集合)链接htm

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

查询效率:索引

一直以来认为exists比in效率高的说法是不许确的,若是查询的两个表大小至关,那么用in和exists差异不大;get

若是两个表中一个较小一个较大,则子查询表大的用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

相关文章
相关标签/搜索