技术文章和资源

技术文章(时间排序)

热门类别

Python PHP MySQL JDBC Linux

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

mysqlmysqli database

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

alter table yourTableName add column yourColumnName yourDataType default yourValue;

首先我们创建一个表:

mysql> create table alterTableDemo
   -> (
   -> Id int,
   -> Name varchar(10)
   -> );
Query OK, 0 rows affected (0.69 sec)

让我们使用 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)

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

mysql> alter table alterTableDemo add column Age int default 18;
Query OK, 0 rows affected (0.67 sec)
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 命令在表中插入记录。

Following is the query

mysql> insert into alterTableDemo(Id,Name,Age) values(100,'Chris',24);
Query OK, 1 row affected (0.16 sec)

mysql> insert into alterTableDemo(Id,Name) values(101,'Robert');
Query OK, 1 row affected (0.25 sec)

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

mysql> select *from alterTableDemo;

以下是输出。由于我们没有设置‘Robert’的年龄,因此 Age 将设置为默认值 18:

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


相关文章