与 SQL 中 NULL 的比较
ANSI-92 SQL 要求与 NULL
的比较计算结果为“falsy”,例如:
SELECT * FROM table WHERE field = NULL
SELECT * FROM table WHERE field != NULL
两者都不会返回任何行,因为 NULL
无法比较像那样。相反,必须使用谓词 IS NULL
和 IS NOT NULL
:
SELECT * FROM table WHERE field IS NULL
SELECT * FROM table WHERE field IS NOT NULL
研究表明 Oracle 1、PostgreSQL、MySQL 和 SQLite全部支持 ANSI 语法。添加到该列表中 DB2 和 Firebird。
除了关闭 ANSI_NULLS
的 SQL Server 之外,还有哪些 RDBMS 支持非 ANSI 语法?
1 尽管整个空字符串 = NULL
混乱。
ANSI-92 SQL mandates that comparisons with NULL
evaluate to "falsy," eg:
SELECT * FROM table WHERE field = NULL
SELECT * FROM table WHERE field != NULL
Will both return no rows because NULL
can't be compared like that. Instead, the predicates IS NULL
and IS NOT NULL
have to be used instead:
SELECT * FROM table WHERE field IS NULL
SELECT * FROM table WHERE field IS NOT NULL
Research has shown me that Oracle 1, PostgreSQL, MySQL and SQLite all support the ANSI syntax. Add to that list DB2 and Firebird.
Aside from SQL Server with ANSI_NULLS
turned off, what other RDBMS support the non-ANSI syntax?
1 The whole empty string = NULL
mess notwithstanding.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就其价值而言,将某些内容与 NULL 进行比较并不是完全错误的,而是未知。此外,
NOT
未知仍然是未知的。ANSI SQL-99 定义了一个谓词
IS [NOT] DISTINCT FROM
。这允许您在比较中混合空值和非空值,并且始终得到 true 或 false。以这种方式,Null 与 null 相比为 true,否则任何非 null 与 null 相比都是 false。所以否定的作用正如你所期望的那样。PostgreSQL、IBM DB2 和 Firebird 确实支持
IS [NOT] DISTINCT FROM
。MySQL 有一个类似的空安全比较运算符
<=>
,如果操作数相同则返回 true,如果不同则返回 false。甲骨文有一条最艰难的路。您必须发挥创意,使用
NVL()
或布尔表达式:讨厌。
For what it's worth, comparing something to NULL is not strictly false, it's unknown. Furthermore,
NOT
unknown is still unknown.ANSI SQL-99 defines a predicate
IS [NOT] DISTINCT FROM
. This allows you to mix nulls and non-null values in comarisons, and always get a true or false. Null compared to null in this way is true, otherwise any non-null compared to null is false. So negation works as you probably expect.PostgreSQL, IBM DB2, and Firebird do support
IS [NOT] DISTINCT FROM
.MySQL has a similar null-safe comparison operator
<=>
that returns true if the operands are the same and false if they're different.Oracle has the hardest path. You have to get creative with use of
NVL()
or boolean expressions:Yuck.
这里是 SQLite、PostgreSQL、Oracle、Informix、DB2、MS 中 null 处理的一个很好的比较 - SQL、OCELOT、MySQL 3.23.41、MySQL 4.0.16、Firebird、SQL Anywhere 和 Borland Interbase
Here is a nice comparison of null handling in SQLite, PostgreSQL, Oracle, Informix, DB2, MS-SQL, OCELOT, MySQL 3.23.41, MySQL 4.0.16, Firebird, SQL Anywhere, and Borland Interbase