为了处理这种情况,MySQL提供了三大运算符:
- IS NULL: 当列的值是 NULL,此运算符返回 true
- IS NOT NULL: 当列的值不为 NULL, 运算符返回 true。
- <=>: 比较操作符(不同于 = 运算符),当比较的的两个值相等或者都为 NULL 时返回 true。
关于 NULL 的条件比较运算是比较特殊的。你不能使用 = NULL 或 != NULL 在列中查找 NULL 值 。
在 MySQL 中,NULL 值与任何其它值的比较(即使是 NULL)永远返回 NULL,即 NULL = NULL 返回 NULL 。
MySQL 中处理 NULL 使用 IS NULL 和 IS NOT NULL 运算符。
注意:
select * , columnName1+ifnull(columnName2,0) from tableName;
columnName1,columnName2 为 int 型,当 columnName2 中,有值为 null 时,columnName1+columnName2=null, ifnull(columnName2,0) 把 columnName2 中 null 值转为 0。
mysql> SELECT *,IFNULL(address,"0") FROM exmaple_userinfo;
+-----------+------+------+--------------------+---------------------+
| name | sex | age | address | IFNULL(address,"0") |
+-----------+------+------+--------------------+---------------------+
| 小伙子 | 男 | 18 | NULL | 0 |
| 男神 | 男 | 18 | 深圳市南山区 | 深圳市南山区 |
| 男神1 | 男 | 18 | 深圳市南山区 | 深圳市南山区 |
| 男神2 | 男 | 18 | 深圳市南山区 | 深圳市南山区 |
+-----------+------+------+--------------------+---------------------+
4 rows in set (0.00 sec)
- is null
mysql> SELECT * FROM exmaple_userinfo where address is null ;
+-----------+------+------+---------+
| name | sex | age | address |
+-----------+------+------+---------+
| 小伙子 | 男 | 18 | NULL |
+-----------+------+------+---------+
1 row in set (0.00 sec)
- is no null
mysql> SELECT * FROM exmaple_userinfo where address is not null ;
+---------+------+------+--------------------+
| name | sex | age | address |
+---------+------+------+--------------------+
| 男神 | 男 | 18 | 深圳市南山区 |
| 男神1 | 男 | 18 | 深圳市南山区 |
| 男神2 | 男 | 18 | 深圳市南山区 |
+---------+------+------+--------------------+
3 rows in set (0.00 sec)