当我将空字符串插入声明为NOT NULL的MySQL列中时,数据类型扮演什么角色?

当我们将空字符串插入声明为NOT NULL的MySQL列中时,结果集中的空字符串表示形式取决于数据类型。我们知道,在插入空字符串时,我们正在为整数提供表示为INT 0的MySQL提供值。

现在,如果该列具有INTEGER数据类型,则MySQL将在结果集中显示0,因为该空字符串已被映射为整数的零。

示例

mysql> create table test(id int NOT NULL, Name Varchar(10));

mysql> Insert into test(id, name) values('1', 'Gaurav'),('0','Rahul'),('','Aarav');
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));

mysql> Insert into test123(id, name) values('1', 'Gaurav'),('0','Rahul'),('','Aarav');
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列中时,数据类型将扮演什么角色。

猜你喜欢