sql - 如果发生 NULL,Where 子句拒绝行

标签 sql sql-server sql-server-2008 null isnull

一个理论问题...

当触发下面给出的一组查询时...

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

...给出...

Actual Result

我用过A.C1 <> B.C1Where条款。

<小时/> 但我预计...

enter image description here

为了获得预期结果作为输出,我需要使用 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 nullis 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/

相关文章:

sql - 如何在 SQL 游标中进行更改

sql-server-2008 - SQL Server Management Studio Intellisense 的问题

sql - Oracle 中的复杂左外连接,转换为 PostgreSQL

SQL:LIKE where 条件指定一个字母后跟一个数字,然后是其他任何东西?

SQL Server/T-SQL : Does CHOOSE evaluate all results, 还是只是返回的结果?

mysql - SQL Server Compact Edition 和 SQL Server Express Edition 之间有什么区别吗?

sql - 如果数据不同,联合返回两行,如果相同则返回一行!为什么?

java - Dynamic Querydsl 根据搜索结果过滤谓词

sql - 创建 JSON 并编辑复杂查询 (oracle 11g)

sql - Rails - has_one 与 WHERE 和 ORDER 的关系?