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');

猜你喜欢

转载自blog.csdn.net/weixin_63610637/article/details/129708751
今日推荐