简体   繁体   English

!=在MySQL中无法正常工作

[英]!= in MySQL not working as I expected

I have a query that worked fine, and then I wanted to add to the the existing where condition something like: and some_column != 1 我有一个工作正常的查询,然后我想向现有的where条件中添加类似以下内容:and some_column!= 1

That column value was null. 该列值为空。 But the query stopped finding the row it used to find. 但是查询停止查找它曾经查找的行。 Any idea why? 知道为什么吗?

Thanks. 谢谢。 Alex 亚历克斯

SQL in just about every form is notorious with its handling of null values in comparisons. 几乎每种形式的SQL都以处理比较中的空值而臭名昭著。 If a column is nullable and you want to do a comparison on it, you should use ISNULL: 如果列是可为空的,并且想要对其进行比较,则应使用ISNULL:

WHERE ISNULL(column_name, -1) != 0

That should take care of your problem. 那应该解决您的问题。

Almost any expression with null is null. 几乎所有带有null的表达式都为null。 1 != null is UNKNOWN (and therefore would cause the row to be removed from the resultset). 1 != null为UNKNOWN(因此将导致该行从结果集中删除)。 1 = null is UNKNOWN. 1 = null为未知。 1 + null is UNKNOWN. 1 + null为未知。

The most significant exception: null is null is TRUE. 最重要的例外: null is null为TRUE。

NULL, by definition, is an "unknown value"... Therefore, null != 1 is an unknown result. 顾名思义,NULL是“未知值” ...因此,null!= 1是未知结果。 The NULL might be 1, and it might not be - but the key is that SQL will not attempt to guess. NULL 可能是1,也可能不是-但关键是SQL不会尝试猜测。 This is sort of a weird way for SQL to handle the value, but it is what it is. 这是SQL处理值的一种怪异方式,但事实就是如此。

Therefore, if you want to account for possible nulls you need to change your where to this: 因此,如果要考虑可能的空值,则需要更改此位置:

AND some_column != 1 AND some_column IS NOT NULL

使用'<>'可能有效...可以尝试

where ISNULL(coloumn_name,1) <> 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM