MYSQL數據庫NULL和空值實驗

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)


結論:使用 count 會過濾掉 NULL 值,但是不會過濾掉空值。


總結
1、空值不佔空間,NULL值佔空間(佔用一個字節)。
2、當字段不爲NULL時,也可以插入空值。
3、當使用 IS NOT NULL 或者 IS NULL 時,只能查出字段中沒有不爲NULL的或者爲 NULL 的,不能查出空值。
4、使用 <> 查詢時,會篩選掉空值和NULL值。
5、使用 count 統計時會過濾掉 NULL 值,但是不會過濾掉空值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章