SQL:exists/not exists、in/not in

exists/not exists

select * from table_name where [not] exists(子查询);
1、首先查询select * from table_name的结果
2、将外查询的结果按行代入到子查询,看子查询有没有结果。
3、子查询有结果,exists返回true,not exists返回false;子查询无结果,exists返回false,not exists返回true。
4、返回true则将代入行显示出来,返回false则将带入行隐藏(不显示)。
5、当外查询的结果按行全部代入到子查询中,得到的新的查询结果即该语句的查询结果。
当外大子小时,即查询的内容很大时,判断次数少,in优于exist【子查询小用in】
当外小子大时,即查询内容很小时,代入次数少,exists优于in【子查询大用exists】
将外查询的每一行代入子查询,看exists或not exists返回true还是false。
true则显示,false则不显示。
exists或not exists即是在外查询的结果上,再做一次筛选。
先运行外查询,再运行子查询。
select * from A where not exists(select * from B where A.id = B.id);
select * from A where exists(select * from B where A.id = B.id);
1,首先执行外查询select * from A,然后从外查询的数据取出一条数据传给内查询。
2,内查询执行select * from B,外查询传入的数据和内查询获得数据根据where后面的条件做匹对,如果存在数据满足A.id=B.id则返回true,如果一条都不满足则返回false。
3,内查询返回true,则外查询的这行数据保留,反之内查询返回false则外查询的这行数据不显示。外查询的所有数据逐行查询匹对。
not exists和exists的用法相反!

实战代码:

select *
from
     WF_LCRZ lcrz
where lcrz.ZXRBH = '121409'
  and lcrz.SJCLSJ >= '20220903000000'
  and exists (select id from WF_LCSL where lcrz.LCSLBH=WF_LCSL.ID and WF_LCSL.lczt <= 2)
  and exists(select id from WF_HJSL where lcrz.HJSLBH=WF_HJSL.ID and WF_HJSL.bz = 0)
  and exists(select id from WF_RWSL where lcrz.RWSLBH=WF_RWSL.ID and WF_RWSL.CLJG='2')
  and not exists (select id from WF_RWFPSL where lcrz.RWFPBH=WF_RWFPSL.id and type=6

注意:

若from后关联的有该表,就不用使用exists,直接在where后加判断就行了,即适用于:不关联该表,但要筛选的时候。


in/not in

in:存在与...里面的 not in :不存在与..里面的
SELECT * 
FROM Store_Information 
WHERE Store_Name IN ('Los Angeles', 'San Diego');

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

袁梦码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值