如何在MySQL中使用alter添加列?

以下是在MySQL中使用alter来添加列的语法:

alter table yourTableName add column yourColumnName yourDataType default yourValue;

让我们首先创建一个表:

mysql> create table alterTableDemo
   -> (
   -> Id int,
   -> Name varchar(10)
   -> );

让我们使用DESC命令检查表的描述。这将显示表的字段,类型,键等:

mysql> desc alterTableDemo;

这将产生以下输出

+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| Id    | int(11)     | YES  |     | NULL    |       |
| Name  | varchar(10) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

现在,添加默认值18的Age列。如果用户不为Age列提供值,则MySQL将使用Age列的默认值。以下是使用alter命令添加列的查询。

mysql> alter table alterTableDemo add column Age int default 18;
Records: 0 Duplicates: 0 Warnings: 0

让我们再次检查表描述:

mysql> desc alterTableDemo;

这将产生以下输出

+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| Id    | int(11)     | YES  |     | NULL    |       |
| Name  | varchar(10) | YES  |     | NULL    |       |
| Age   | int(11)     | YES  |     | 18      |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

让我们使用insert命令在表中插入记录。

以下是查询

mysql> insert into alterTableDemo(Id,Name,Age) values(100,'Chris',24);

mysql> insert into alterTableDemo(Id,Name) values(101,'Robert');

以下是使用select语句显示表中所有记录的查询:

mysql> select *from alterTableDemo;

以下是输出。由于我们尚未为“罗伯特”设置年龄,因此将为“年龄”设置默认值18:

+------+--------+------+
| Id   | Name   | Age  |
+------+--------+------+
| 100  | Chris  | 24   |
| 101  | Robert | 18   |
+------+--------+------+
2 rows in set (0.00 sec)