!= 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
开发者_运维百科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. If a column is nullable and you want to do a comparison on it, you should use ISNULL:
WHERE ISNULL(column_name, -1) != 0
That should take care of your problem.
Almost any expression with null is null. 1 != null
is UNKNOWN (and therefore would cause the row to be removed from the resultset). 1 = null
is UNKNOWN. 1 + null
is UNKNOWN.
The most significant exception: null is null
is TRUE.
NULL, by definition, is an "unknown value"... Therefore, null != 1 is an unknown result. The NULL might be 1, and it might not be - but the key is that SQL will not attempt to guess. This is sort of a weird way for SQL to handle the value, but it is what it is.
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
using '<>' may work...can give a try
where ISNULL(coloumn_name,1) <> 1
精彩评论