在MySQL中,为什么我的NULL值不能正确比较?
问题描述:
我有以下表在MySQL中,为什么我的NULL值不能正确比较?
Select * from Peeps
Id Name Age
1 Sam 16
2 John NULL
Select
Name,
Age,
(If Age=NULL,1,0) AS Z
from peeps;
结果:
+------+------+---+
| name | age | Z |
+------+------+---+
| Sam | 16 | 0 |
| John | NULL | 0 |
+------+------+---+
预期的效果
+------+------+---+
| name | age | Z |
+------+------+---+
| Sam | 16 | 0 |
| John | NULL | 1 |
+------+------+---+
答
尝试:
Select
Name,
Age,
(If Age IS NULL,1,0) AS Z
from peeps;
http://dev.mysql.com/doc/refman/5.1/en/working-with-null.html
答
使用这个代替:
IF Age IS NULL
使用NULL实际上将表示空值,而“NULL”将充当字母N-U-L-L的字符串。根本不一样。
最终查询:
SELECT Name,
Age,
(IF Age IS NULL, 1, 0) AS Z
FROM peeps