在表中创建一个允许为空但默认值为 (非空) 空字符串的列?


你需要使用 `default` 关键字。语法如下:

alter table yourTableName add yourColumnName yourDataType NULL Default '';

为了理解上述语法,让我们创建一个表。创建表的查询如下:

mysql> create table AllowNullDefaulNotNullDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> UserName varchar(20),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.65 sec)

让我们添加一个允许 NULL 值但默认值设置为非 NULL 的新列。查询如下:

mysql> alter table AllowNullDefaulNotNullDemo add UserAddress varchar(20) NULL Default'';
Query OK, 0 rows affected (1.04 sec)
Records: 0 Duplicates: 0 Warnings: 0

现在使用 DESC 命令检查表的描述。查询如下:

mysql> desc AllowNullDefaulNotNullDemo;

以下是输出:

+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| Id          | int(11)     | NO   | PRI | NULL    | auto_increment |
| UserName    | varchar(20) | YES  |     | NULL    |                |
| UserAddress | varchar(20) | YES  |     |         |                |
+-------------+-------------+------+-----+---------+----------------+
3 rows in set (0.17 sec)

现在您可以使用 insert 命令在表中插入一些记录。在下面的查询中,UserAddress 列允许 NULL 值,但默认值设置为非 NULL。

让我们向该列插入记录。查询如下:

mysql> insert into AllowNullDefaulNotNullDemo(UserAddress) values('US');
Query OK, 1 row affected (0.14 sec)
mysql> insert into AllowNullDefaulNotNullDemo(UserAddress) values(NULL);
Query OK, 1 row affected (0.16 sec)
mysql> insert into AllowNullDefaulNotNullDemo() values();
Query OK, 1 row affected (0.12 sec)

检查新添加列 UserAddress 的特定记录。查询如下:

mysql> select UserAddress from AllowNullDefaulNotNullDemo;

以下是输出:

+-------------+
| UserAddress |
+-------------+
| US          |
| NULL        |
|             |
+-------------+
3 rows in set (0.00 sec)

更新于:2019年7月30日

584 次浏览

启动您的职业生涯

完成课程后获得认证

开始学习
广告
© . All rights reserved.