您可以通过使用IS NOT
而不是!=
. 如果您查看本文档的操作符部分,您会看到:
IS 和 IS NOT 运算符的工作方式与 = 和 != 类似,除非其中一个或两个操作数为 NULL。在这种情况下,如果两个操作数都为 NULL,则 IS 运算符的计算结果为 1(真),而 IS NOT 运算符的计算结果为 0(假)。如果一个操作数为 NULL 而另一个不是,则 IS 运算符的计算结果为 0(假)并且 IS NOT 运算符为 1(真)。IS 或 IS NOT 表达式不可能计算为 NULL。运算符 IS 和 IS NOT 与 = 具有相同的优先级。
我自己对此进行了测试:
sqlite> create table temp( dataColumn, nullColumn );
sqlite> insert into temp( dataColumn, nullColumn ) values ( 'test', NULL );
sqlite> select * from temp where nullColumn != 'test';
sqlite> select * from temp where nullColumn IS NOT 'test';
test|
sqlite> select * from temp where dataColumn IS NOT 'test';
sqlite>
从更多的游戏来看,当你使用它来比较某些东西时,!=
运算符似乎会评估为:NULL
NULL
sqlite> select ( 'contents' != NULL );
sqlite> select ( 'contents' == NULL );
sqlite> select ( 'contents' IS NULL );
0
sqlite> select ( 'contents' IS NOT NULL );
1
大概这就是为什么你没有得到你期望的行为 - 你实际上是在说WHERE NULL != 'contents'
哪个评估为 NULL,并且不满足 WHERE 子句