in和exists的区别和关系

in 后面是跟具体的值

exists 在后面的子查询中 只返回true or false 即查询到数据返回true 没有查询到数据返回false 因此这里的select 可以是任何字段 1 或者 a z或者 。。。。。 select null 是等于true

在效率上 in 比 exists 要快 in 更高效
在执行顺序上,In 和 exists 不一样
in后面的子查询先产生结果集,然后主查询再去结果集里面去找符合要求的字段,符合要求的输出。

select * 
  from stu
 where sex='男'
   and age in (select age 
                 from stu 
                where sex='女') 

not in :主查询时表大,子查询中的表小 用not In 。执行顺序 是表中一条一条记录的去匹配,不走索引。

not exists 的执行顺序 在表中查询是根据索引去查询,找到就返回true ,不会每条记录都去查询

not exists查询效率比not In 高很多

查询哪些班级没有学生

select * 
  from class
 where cid not in (select 
                   distinct cid
				   from stu
 )  

当表中cid存在Null值时,not in 不对其进行处理

优化:

select * 
  from class
 where cid not in (select 
                   distinct cid
				   from stu
				   where cid is not null
 )  

查询哪些班级中没有学生

select * 
  from class2
 where not exists (select 
                   *
				   from stu1
				   where stu1.cid= class2.cid)  

not exists的执行顺序 在表中查询是根据索引去查询,找到就返回true ,不会每条记录都去查询

not exists查询效率比not In 高很多

转载

https://www.cnblogs.com/qlqwjy/p/8598091.html

实例 1

实例 2
在这里插入图片描述
实例 3

在这里插入图片描述

在这里插入图片描述

口诀

1 全部选了 用双重否定表示肯定 not exists not exists
2 没有全部选,先exists, 后 not exists
3 什么都没选 先not exists , 后exists
4 至少选择了一个 ,两个exists

参考文献

https://blog.csdn.net/daobuxinzi/article/details/124617622

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值