not exists用法

有两个简单例子,以说明 “exists”和“in”的效率问题

select * from T1 where exists(select 1 from T2 where T1.a=T2.a) ;

T1数据量小而T2数据量非常大时,T1<<T2 时,1) 的查询效率高。

select * from T1 where T1.a in (select T2.a from T2) ;

T1数据量非常大而T2数据量小时,T1>>T2 时,2) 的查询效率高。

not exists是sql中的一个语法,常用在子查询和主查询之间,用于条件判断,根据一个条件返回一个布尔值,从而来确定下一步操作如何进行,not exists也是exists或in的对立面。

not exists 是exists的对立面,所以要了解not exists的用法,我们首先了解下exists、in的区别和特点:

exists : 强调的是是否返回结果集,不要求知道返回什么, 比如:

注意:

上述 1)中的有加粗字体的部分 ,理解其含义;

其中 “select 1 from T2 where T1.a=T2.a” 相当于一个关联表查询,相当于

“select 1 from T1,T2 where T1.a=T2.a”

但是,如果你当当执行 1) 句括号里的语句,是会报语法错误的,这也是使用exists需要注意的地方。

“exists(xxx)”就表示括号里的语句能不能查出记录,它要查的记录是否存在。

因此“select 1”这里的 “1”其实是无关紧要的,换成“2”也没问题,它只在乎括号里的数据能不能查找出来,是否存在这样的记录,如果存在,这 1) 句的where 条件成立。

而not exists 和not in 分别是exists 和 in 的 对立面。

exists (sql 返回结果集,为真)
1
主要看exists括号中的sql语句结果是否有结果,有结果:才会继续执行where条件;没结果:视为where条件不成立。

not exists (sql 不返回结果集,为真)
1
主要看not exists括号中的sql语句是否有结果,无结果:才会继续执行where条件;有结果:视为where条件不成立。

**

not exists:经过测试,当子查询和主查询有关联条件时,相当于从主查询中去掉子查询的数据

**

例如:

test数据:id name

1 张三

2 李四

 

select * from test c where  not exists

(select 1 from test t where t.id= '1' )

--无结果

select * from test c where  not exists

(select 1 from test t where t.id= '1'  and t.id = c.id)

--返回2 李四

 


原文链接:https://blog.csdn.net/Dreamy_zsy/article/details/114539575

posted @ 2022-09-09 16:54  aaa111js  阅读(4341)  评论(0编辑  收藏  举报