sql语句中not in和exists 的用法以及更新两个表数据的插入实例

以下内容来源于网络按个人理解接合而成。 

1、而 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”。原因自己想啊。

  

ok,说完了,下面就几个方面比较一下吧(虽然意义不是很大,呵呵)

写法上:

当然是in、not in最直观了(地球人都知道)。

 

 

再说效率问题(仅限DB2,原因不用说了吧)

in效率比exists高

not exists效率比not in高

具体执行时间如下

in      0.01 secs

exists  0.03 secs

not in      8.62 secs

not exists  0.03 secs

 

总结:

       多字段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)


本博客所有文章如无特别注明均为原创。作者:樱木复制或转载请以超链接形式注明转自 EFE
原文地址《sql语句中not in和exists 的用法以及更新两个表数据的插入实例
分享到:更多

相关推荐

发表评论

路人甲 表情
Ctrl+Enter快速提交

网友评论(0)