IN和EXISTS的区别浅谈

exists 与 in 最大的区别在于 in引导的子句只能返回一个字段;

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

1. 先说“in”。
从表b里查询出满足条件“select aaa,bbb from a”的记录:
如下语句就是我们想要的结果:
select * from b where (aaa,bbb)  in ( select aaa,bbb from a );
不过很可惜,上面的语句只能再DB2上执行,SQL Server不行
还好可以用下面的语句来代替
select * from b where  exists ( select * from a where a.aaa=b.aaa and a.bbb=b.bbb);
 
当然你可能会说我的条件是“select aaa,bbb from a where 表a某字段1='...' and 表a某字段2>1111” 什么等等,我就权且用“查询条件A”代表了
即:查询条件A = 表a某字段1='...' and 表a某字段2>1111
那语句就该这么写了
select * from b where (aaa,bbb)  in ( select aaa,bbb from a where 查询条件A);
select * from b where  exists ( select * from a where a.aaa=b.aaa and a.bbb=b.bbb and 查询条件A);
用exists时,最好把“查询条件A”中的“表a某字段1”之类写为“a.表a某字段1”。原因自己想啊。
 
2. 再说“not in”。基本和“in”一样
从表b里查询出不在结果集“select aaa,bbb from a”中的记录:
如下语句就是我们想要的结果:
select * from b where (aaa,bbb) not in ( select aaa,bbb from a );
不过很可惜,上面的语句只能再DB2上执行,SQL Server不行
还好可以用下面的语句来代替
select * from b where not exists ( select * from a where a.aaa=b.aaa and a.bbb=b.bbb);
 
当然你可能会说我的条件是“select aaa,bbb from a where 表a某字段1='...' and 表a某字段2>1111” 什么等等,我就权且用“查询条件A”代表了
即:查询条件A = 表a某字段1='...' and 表a某字段2>1111
那语句就该这么写了
select * from b where (aaa,bbb) not in ( select aaa,bbb from a where 查询条件A);
select * from b where not exists ( select * from a where a.aaa=b.aaa and a.bbb=b.bbb and 查询条件A);
用not exists时,最好把“查询条件A”中的“表a某字段1”之类写为“a.表a某字段1”。
  
写法上:
当然是in、not in最直观了(地球人都知道)。
 
再说效率问题(仅限DB2,原因不用说了吧):
in效率比exists高
not exists效率比not in高

总结:
       多字段in、not in在db2数据中可以执行,SQL Server不行
       exists、not exists在db2,SQL Server均可执行
       而且总体上用exists,not exists 效率都很高,建议大家还是用好exists,not exists吧!
把表yyy的不同记录添加到XXX表中(两个表结构相同)
insert into xxx select  merchant_id(这里应该把除了自增ID外的字段都写入)  from yyy a
      where not exists  (select * from yyy b   where a.card_id=b.card_id and a.value=b.value)
 

猜你喜欢

转载自blog.csdn.net/weixin_41648325/article/details/81354157
今日推荐