在oracle中,“not exists”用于判断子句是否返回结果集,若子句返回结果集为false,若子句没有返回结果集则为true,语法为“select * from daul where not exists(子句查询条件)”。
本教程操作环境:windows10系统、oracle 11g版、dell g3电脑。
oracle中not exists的用法是什么exists : 强调的是是否返回结果集,不要求知道返回什么, 比如:
select name from student where sex = 'm' and mark exists(select 1 from grade where ...)
只要exists引导的子句有结果集返回,那么exists这个条件就算成立了,大家注意返回的字段始终为1,如果改成“select 2 from grade where ...”,那么返回的字段就是2,这个数字没有意义。所以exists子句不在乎返回什么,而是在乎是不是有结果集返回。
而 exists 与 in 最大的区别在于 in引导的子句只能返回一个字段,比如:
select name from student where sex = 'm' and mark in (select 1,2,3 from grade where ...)
,in子句返回了三个字段,这是不正确的,exists子句是允许的,但in只允许有一个字段返回,在1,2,3中随便去了两个字段即可。
而not exists 和not in 分别是exists 和 in 的 对立面。
exists (sql 返回结果集为真)
not exists (sql 不返回结果集为真)
下面详细描述not exists的过程:
如下:
表a
id name
1 a1
2 a2
3 a3
表b
id aid name
1 1 b1
2 2 b2
3 2 b3
表a和表b是1对多的关系 a.id => b.aid
select id,name from a where exists (select * from b where a.id=b.aid)
执行结果为
1 a1
2 a2
原因可以按照如下分析
select id,name from a where exists (select * from b where b.aid=1)--->select * from b where b.aid=1有值返回真所以有数据select id,name from a where exists (select * from b where b.aid=2)--->select * from b where b.aid=2有值返回真所以有数据select id,name from a where exists (select * from b where b.aid=3)--->select * from b where b.aid=3无值返回真所以没有数据
not exists 就是反过来
select id,name from a where not exist (select * from b where a.id=b.aid)
执行结果为
3 a3
exists = in,意思相同不过语法上有点点区别,好像使用in效率要差点,应该是不会执行索引的原因
select id,name from a where id in (select aid from b)
not exists = not in ,意思相同不过语法上有点点区别
select id,name from a where id not in (select aid from b)
有时候我们会遇到要选出某一列不重复,某一列作为选择条件,其他列正常输出的情况.
推荐教程:《oracle视频教程》
以上就是oracle中not exists的用法是什么的详细内容。