create table test_null (
cola varchar(255) not null,
colb varchar(255) default null
) engine=innodb default charset=utf8;
(root:)[test]> show create table test_null\G
*************************** 1. row ***************************
Table: test_null
Create Table: CREATE TABLE `test_null` (
`colA` varchar(255) NOT NULL,
`colB` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
insert into `test_null`(`cola`, `colb`) values (null, null);
(root:)[test]> insert into `test_null`(`cola`, `colb`) values (null, null);
ERROR 1048 (23000): Column 'colA' cannot be null
--插入空值
insert into `test_null`(`cola`, `colb`) values ('', '');
(root:)[test]> select * from test_null;
+------+------+
| colA | colB |
+------+------+
| | |
+------+------+
1 row in set (0.00 sec)
insert into `test_null`(`cola`, `colb`) values ('1', '2');
insert into `test_null`(`cola`) values ('1');
(root:)[test]> select * from test_null;
+------+------+
| colA | colB |
+------+------+
| | |
| 1 | 2 |
| 1 | NULL |
+------+------+
3 rows in set (0.00 sec)
select * from `test_null` where cola is not null;
(root:)[test]> select * from `test_null` where cola is not null;
+------+------+
| colA | colB |
+------+------+
| | |
| 1 | 2 |
| 1 | NULL |
+------+------+
3 rows in set (0.00 sec)
select * from `test_null` where colb is not null;
(root:)[test]> select * from `test_null` where colb is not null;
+------+------+
| colA | colB |
+------+------+
| | |
| 1 | 2 |
+------+------+
2 rows in set (0.00 sec)
結論:使用 IS NOT NULL 查詢不會過濾空值,但是會過濾掉NULL。
select * from `test_null` where cola <> '';
(root:)[test]> select * from `test_null` where colb <> '';
+------+------+
| colA | colB |
+------+------+
| 1 | 2 |
+------+------+
1 row in set (0.00 sec)
結論:使用 <> 會過濾掉NULL和空值。
select count(colb) from `test_null`;
(root:)[test]> select count(colb) from `test_null`;
+-------------+
| count(colb) |
+-------------+
| 2 |
+-------------+
1 row in set (0.01 sec)