首页 > 数据库技术 > 详细

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

时间:2019-06-20 10:53:01      阅读:119      评论:0      收藏:0      [点我收藏+]

前言:

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

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

原文:https://www.cnblogs.com/huashengweilong/p/11056183.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!