SQL之NULL值的幾種處理方式
1、建立測試表:
drop table if exists tab_null_operator;
create table tab_null_operator as
select 1 as id,'chavin' as name union all
select 2 as id,'nope' as name union all
select 3 as id,'' as name union all
select 4 as id,'' as name union all
select 5 as id,null as name union all
select 6 as id,null as name union all
select 7 as id,' ' as name union all
select 8 as id,' ' as name union all
select 9 as id,' ' as name union all
select 10 as id,' ' as name
;
2、檢視資料:
mysql> select * from tab_null_operator;
+----+--------+
| id | name |
+----+--------+
| 1 | chavin |
| 2 | nope |
| 3 | |
| 4 | |
| 5 | NULL |
| 6 | NULL |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
+----+--------+
10 rows in set (0.00 sec)
小結:從結果我們可以看出,id in (5,6)的兩個值是null,id in (1,2)的是字串,id in (3,4,7,8,9,10)從結果看均是空字串,實際id in (3,4)是空字串,id in (7,8)是單個空格字串,id in (9,10)是\t字串。
3、查詢name為null的記錄:
mysql> select * from tab_null_operator where name is null;
+----+------+
| id | name |
+----+------+
| 5 | NULL |
| 6 | NULL |
+----+------+
2 rows in set (0.00 sec)
小結:可以看到只有id in (5,6)的記錄name欄位才是真正的null。
4、查詢name為''的記錄資訊:
mysql> select * from tab_null_operator where name = '';
+----+------+
| id | name |
+----+------+
| 3 | |
| 4 | |
| 7 | |
| 8 | |
+----+------+
4 rows in set (0.00 sec)
小結:可以看到我們輸入的以空格為字串的值都表現為空字串。然後\t字串的缺沒有篩選出來。
5、查詢\t字串的資料:
mysql> select * from tab_null_operator where name = ' ';
+----+------+
| id | name |
+----+------+
| 9 | |
| 10 | |
+----+------+
2 rows in set (0.00 sec)