上午调一段代码死活调不过,耽误了一上午的时间,终于知道是哪儿错了。如果早点来CSDN上问下或许可以省点时间~_~
先说一个简单的情况:
select 1 where 1 in (1,null)
select 1 where 1 not in (2,null)按我原来的理解,两条语句都会返回1,但第2句话实际返回的是空集(这儿我非常不理解,虽然sql server就是这么规定的~_~ )
更复杂的情况:标记b处的句子不能满足我的原意(返回空集而非ID为1的记录),必须按c处的写法才可以declare @t1 table(id int)
declare @t2 table(id int)insert into @t1 values (1)
insert into @t1 values (2)
insert into @t1 values (3)insert into @t2 values (2)
insert into @t2 values (3)
insert into @t2 values (null) b: select * from @t1 where id not in (select distinct id from @t2)
select * from @t1 where not id in (select distinct id from @t2)c: select * from @t1 where id not in (select distinct id from @t2 where id is not null)
select * from @t1 where not id in (select distinct id from @t2 where id is not null)
先说一个简单的情况:
select 1 where 1 in (1,null)
select 1 where 1 not in (2,null)按我原来的理解,两条语句都会返回1,但第2句话实际返回的是空集(这儿我非常不理解,虽然sql server就是这么规定的~_~ )
更复杂的情况:标记b处的句子不能满足我的原意(返回空集而非ID为1的记录),必须按c处的写法才可以declare @t1 table(id int)
declare @t2 table(id int)insert into @t1 values (1)
insert into @t1 values (2)
insert into @t1 values (3)insert into @t2 values (2)
insert into @t2 values (3)
insert into @t2 values (null) b: select * from @t1 where id not in (select distinct id from @t2)
select * from @t1 where not id in (select distinct id from @t2)c: select * from @t1 where id not in (select distinct id from @t2 where id is not null)
select * from @t1 where not id in (select distinct id from @t2 where id is not null)
select ... from ... where id not in (...)只要(...)中包含null,必然返回空集合
not in() 是AND關系
不过我加了where id is not null就解决了
select * from @t1 where id not in (select distinct id from @t2 where id is not null)
and id is not null
select 1 from (1=null) or (1=2)
select 1 from (1<>null) and (1<>2)显然:
true OR null =true
true and null=null当然结果就是楼主看到的了
接分!~
加IS NOT NULL OR <>''
select 1 where 1 not in (2,null)
set ansi_nulls on默认情况下,ANSI_NULLS选项是ON的,此时,根据SQL-92标准的规定:
与NULL的比较均返回为Unknown,不能确定。
如果设置ANSI_NULLS为OFF,则强制不使用SQL-92标准,此时与NULL的比较和与其他值的比较是一样的。
值 用的是 = 或 <>in 或 not in谓词的作用跟后者差不多,只是多了集合的枚举罢了,自然对null用in或not in谓词操作会导致失败并不是什么新鲜玩意把?
我也经常碰到过
不过我加了where id is not null就解决了
select * from @t1 where id not in (select distinct id from @t2 where id is not null)
and id is not null
正解
无
select 1 from dual where not (1 in (null,2))
无
select 1 from dual where not (1 in (null,1))
无
select 1 from dual where (1 in (null,1))
有
本身Transact-SQL 支持在与空值进行比较,允许比较运算符返回 TRUE 或 FALSE。但必须通过设置 ANSI_NULLS OFF 将此选项激活。
当 SET ANSI_NULLS 为 ON 时,如果比较中有一个或多个表达式为 NULL,则既不输出 TRUE 也不输出 FALSE,而是输出 UNKNOWN。这是因为未知值不能与其他任何值进行逻辑比较。(参考SQLSERVER帮助文档)
SET ANSI_NULLS off
select 1 where 1 in (1,null)
select 1 where 1 not in (2,null)
这时结果都会返回1