MySQL: Why is NULL ignored in MySQL?

醉酒当歌 提交于 2019-12-11 15:11:55

问题


I have a table with the following possible values for the column field_value.

But when I try to select all values which are not 'CB', the query result also ignores all NULL values.

Why does this happen?

mysql> select distinct field_value from TableName;
+--------------+
| field_value  |
+--------------+
| S            |
| NULL         |
| CA           |
| CB           |
+--------------+
4 rows in set (6.32 sec)

mysql> select distinct field_value from TableName where field_value!='CB';
+--------------+
| field_value  |
+--------------+
| S            |
| CA           |
+--------------+
2 rows in set (0.15 sec)

mysql>

回答1:


That's because any comparisons with NULL also yield NULL (i.e. not truthy nor falsy).

The special operators IS NULL and IS NOT NULL are used to make useful comparisons against NULL.

Your query should therefore be:

... WHERE field_value!='CB' OR field_value IS NULL;

See also: Working with NULL values




回答2:


Because NULL is unknown and unknown doesn't mean that is it not equal to CB.

if you want to return null values add a condition (IS NULL) in your query,

SELECT ...
FROM   ...
where field_value != 'CB' OR field_value IS NULL



回答3:


NULL is not equal to any value. NULL is not unequal to any value. NULL is not even equal to NULL. Try it if you don't believe it.

select * from anytable
where NULL = NULL
or not NULL = NULL
or NULL != NULL
or not NULL != NULL

You should get zero rows retrieved. The result of all four conditions is UNKNOWN. unknown is not the same thing as TRUE. unknown is not the same thing as FALSE. If this sounds like a mess to you, then you are probably starting to understand.

It's best to avoid using nullable columns in WHERE conditions, unless you are prepared to think things through very carefully.




回答4:


Actually NULL means “a missing unknown value”

Check this page



来源:https://stackoverflow.com/questions/12966873/mysql-why-is-null-ignored-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!