我們先看一下效果,然后在解釋,示例如下:
mysql> create table test5 (a int not null,b int,c varchar(10)); Query OK, 0 rows affected (0.01 sec) mysql> insert into test5 values (1,2,'a'),(3,null,'b'),(4,5,null); Query OK, 3 rows affected (0.01 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from test5; +---+------+------+ | a | b | c | +---+------+------+ | 1 | 2 | a | | 3 | NULL | b | | 4 | 5 | NULL | +---+------+------+ 3 rows in set (0.00 sec)
上面我們創建了一個表test5,3個字段,a不能為空,b、c可以為空,插入了3條數據,睜大眼睛看效果了:
mysql> select * from test5 where b>0; +---+------+------+ | a | b | c | +---+------+------+ | 1 | 2 | a | | 4 | 5 | NULL | +---+------+------+ 2 rows in set (0.00 sec) mysql> select * from test5 where b<=0; Empty set (0.00 sec) mysql> select * from test5 where b=NULL; Empty set (0.00 sec) mysql> select * from test5 t where t.b between 0 and 100; +---+------+------+ | a | b | c | +---+------+------+ | 1 | 2 | a | | 4 | 5 | NULL | +---+------+------+ 2 rows in set (0.00 sec) mysql> select * from test5 where c like '%'; +---+------+------+ | a | b | c | +---+------+------+ | 1 | 2 | a | | 3 | NULL | b | +---+------+------+ 2 rows in set (0.00 sec) mysql> select * from test5 where c in ('a','b',NULL); +---+------+------+ | a | b | c | +---+------+------+ | 1 | 2 | a | | 3 | NULL | b | +---+------+------+ 2 rows in set (0.00 sec) mysql> select * from test5 where c not in ('a','b',NULL); Empty set (0.00 sec)
認真看一下上面的查詢:
上面帶有條件的查詢,對字段b進行條件查詢的,b的值為NULL的都沒有出現。
對c字段進行like '%'查詢、in、not查詢,c中為NULL的記錄始終沒有查詢出來。
between and查詢,為空的記錄也沒有查詢出來。
結論:查詢運算符、like、between and、in、not in對NULL值查詢不起效。
那NULL如何查詢呢?繼續向下看
IS NULL/IS NOT NULL(NULL值專用查詢)
上面介紹的各種運算符對NULL值均不起效,mysql為我們提供了查詢空值的語法:IS NULL、IS NOT NULL。
IS NULL(返回值為空的記錄)
select 列名 from 表名 where 列 is null;
查詢指定的列的值為NULL的記錄。
如:
mysql> create table test7 (a int,b varchar(10)); Query OK, 0 rows affected (0.01 sec) mysql> insert into test7 (a,b) values (1,'a'),(null,'b'),(3,null),(null,null),(4,'c'); Query OK, 5 rows affected (0.00 sec) Records: 5 Duplicates: 0 Warnings: 0 mysql> select * from test7; +------+------+ | a | b | +------+------+ | 1 | a | | NULL | b | | 3 | NULL | | NULL | NULL | | 4 | c | +------+------+ 5 rows in set (0.00 sec) mysql> select * from test7 t where t.a is null; +------+------+ | a | b | +------+------+ | NULL | b | | NULL | NULL | +------+------+ 2 rows in set (0.00 sec) mysql> select * from test7 t where t.a is null or t.b is null; +------+------+ | a | b | +------+------+ | NULL | b | | 3 | NULL | | NULL | NULL | +------+------+ 3 rows in set (0.00 sec)
IS NULL(返回值不為空的記錄)
select 列名 from 表名 where 列 is not null;
查詢指定的列的值不為NULL的記錄。
如:
mysql> select * from test7 t where t.a is not null; +------+------+ | a | b | +------+------+ | 1 | a | | 3 | NULL | | 4 | c | +------+------+ 3 rows in set (0.00 sec) mysql> select * from test7 t where t.a is not null and t.b is not null; +------+------+ | a | b | +------+------+ | 1 | a | | 4 | c | +------+------+ 2 rows in set (0.00 sec)
