一个理论问题...
当触发下面给出的一组查询时...
Create table Temp1(C1 varchar(2))
Create table Temp2(C1 varchar(2))
insert into Temp1 Values('A'),(NULL),('B')
insert into Temp2 Values('B'),(NULL),('C'),(NULL)
select *from Temp1 A,Temp2 B
where A.C1 <> B.C1
...给出...
我用过A.C1 <> B.C1
在 Where
条款。
为了获得预期结果作为输出,我需要使用 ISNULL(A.C1,'') <> ISNULL(B.C1,'')
在 Where
条款。
我的问题是为什么我需要使用ISNULL
每次都按预期获得输出,如 NULL
不等于任何字符串数据。
最佳答案
引自here很完美:
The correct way to understand NULL is that it is not a value. Not “this is a NULL value” but “this NULL is not a value.” Everything either is a value, or it isn’t. When something is a value, it is “1,” or “hello,” or “green,” or “$5.00″ etc — but when something isn’t a value, it just isn’t anything at all. SQL represents “this has no value” by the special non-value NULL. When someone says “the NULL value,” one should mentally disagree, because there’s no such thing. NULL is the complete, total absence of any value whatsoever.
Null 不等于任何内容,因此比较总是失败。
例如尝试这个查询:
select *
from Temp2 B
where B.C1 = null
它不会返回任何行!
您必须使用的句柄 null is null
或 is not null
:
select *
from Temp1 A, Temp2 B
where A.C1 <> B.C1 or (A.C1 is null and B.C1 is not null) or (B.C1 is null and A.C1 is not null)
返回与使用 ISNULL
查询返回的值完全相同的值。
关于sql - 如果发生 NULL,Where 子句拒绝行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17442229/