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

来源:互联网 发布:objectivec编程 第2版 编辑:程序博客网 时间:2024/05/16 14:42

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

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的哦。