技巧:关于Null与not in以及not exists产生的效果

首先定义两个表,并且插入内容

declare @temp1 table
(
userid varchar(10),
username varchar(50)
)

declare @temp2 table
(
userid varchar(10),
username varchar(50),
grade varchar(100)
)

insert @temp1
select 1,'user1' union all
select 2,null union all
select 3,'user3' union all
select 4,null union all
select 5,'user5' union all
select 6,'user6'

insert @temp2
select 1,'user1',90 union all
select 2,null,80 union all
select 7,'user7',80 union all
select 8,'user8',90 


not  in SQL语句:
select * from @temp2 where username not in (select username from @temp1)因为@temp1表存在null值记录,导致最后的结为0;
而select * from @temp2 where username in (select username from @temp1)的结果为1条记录;
由此可见当not in 从表记录中存在Null记录,即使存在对应记录,结果也为0

 

not exists语句:
select * from @temp2 g where not exists (select 1 from @temp1 t where t.userid=g.userid and t.username=g.username) 结果为3 条记录:包括null、user7及user8

select * from @temp2 g where exists (select 1 from @temp1 t where t.userid=g.userid and t.username=g.username) 结果为1条记录

总结:
当在null记录时,exists与in查询结果一致,但not in 和 not exists结果却有差异,当not in 后面表记录存在Null值时,查询结果为0条记录;not exists却有可以查询出记录;同时应注意null=null也是False的哦。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值