如何修改 MySQL 中的列默认值?
mysqlmysqli database
首先我们创建一个表 −
mysql> create table DemoTable ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserName varchar(20) DEFAULT 'John' ); Query OK, 0 rows affected (0.76 sec)
让我们检查一下表的描述 −
mysql> desc DemoTable;
这将产生以下输出 −
+----------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+----------------+ | UserId | int(11) | NO | PRI | NULL | auto_increment | | UserName | varchar(20) | YES | | John | | +----------+-------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values(); Query OK, 1 row affected (0.17 sec)
以下是使用 select 语句显示表中的所有记录的查询 −
mysql> select *from DemoTable;
这将产生以下输出 −
+--------+----------+ | UserId | UserName | +--------+----------+ | 1 | John | +--------+----------+ 1 row in set (0.00 sec)
这是修改列默认值的查询。我们已将默认用户名设置为 Chris −
mysql> alter table DemoTable modified UserName varchar(20) DEFAULT 'Chris'; Query OK, 0 rows affected (0.19 sec) Records: 0 Duplicates: 0 Warnings: 00
让我们使用 desc 命令检查表的描述 −
mysql> desc DemoTable;
这将产生以下输出 −
+----------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+----------------+ | UserId | int(11) | NO | PRI | NULL | auto_increment | | UserName | varchar(20) | YES | | Chris | | +----------+-------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec)
现在使用插入命令在表中插入一些记录。由于我们尚未添加姓名,因此将添加默认的"Chris" −
mysql> insert into DemoTable values(); Query OK, 1 row affected (0.11 sec)
以下是使用 select 语句显示表中的所有记录的查询 −
mysql> select *from DemoTable;
这将产生以下输出 −
+--------+----------+ | UserId | UserName | +--------+----------+ | 1 | John | | 2 | Chris | +--------+----------+ 2 rows in set (0.00 sec)