【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

转载于:https://www.cnblogs.com/huashengweilong/p/11056183.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值