當我在宣告為 NOT NULL 的 MySQL 列中插入空字串時,資料型別起什麼作用?


當我們將空字串插入宣告為 NOT NULL 的 MySQL 列時,結果集中空字串的表示取決於資料型別。眾所周知,在插入空字串時,我們向 MySQL 提供了一個值為 INT 0 的整數表示。

現在,如果該列的資料型別為 INTEGER,則 MySQL 會在結果集中顯示 0,因為該空字串已被對映為整數零。

示例

mysql> create table test(id int NOT NULL, Name Varchar(10));
Query OK, 0 rows affected (0.19 sec)

mysql> Insert into test(id, name) values('1', 'Gaurav'),('0','Rahul'),('','Aarav');
Query OK, 3 rows affected, 1 warning (0.08 sec)
Records: 3 Duplicates: 0 Warnings: 1

mysql> Select * from test;
+----+--------+
| id | Name   |
+----+--------+
|  1 | Gaurav |
|  0 | Rahul  |
|  0 | Aarav  |
+----+--------+
3 rows in set (0.00 sec)

但是,如果該列具有任何其他資料型別,例如 VARCHAR,則 MySQL 會在結果集中顯示一個空字串。

mysql> create table test123(id Varchar(10) NOT NULL, Name Varchar(10));
Query OK, 0 rows affected (0.19 sec)

mysql> Insert into test123(id, name) values('1', 'Gaurav'),('0','Rahul'),('','Aarav');
Query OK, 3 rows affected, 1 warning (0.08 sec)
Records: 3 Duplicates: 0 Warnings: 1

mysql> Select * from test123;
+----+--------+
| id | Name   |
+----+--------+
|  1 | Gaurav |
|  0 | Rahul  |
|    | Aarav  |
+----+--------+
3 rows in set (0.00 sec)

從以上示例可以看出,當我們在宣告為 NOT NULL 的 MySQL 列中插入空字串時,資料型別起什麼作用。

更新於: 2020-06-22

98 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.