Mariadb 简明教程

MariaDB - Alter Command

ALTER 命令提供了一种修改现有表结构的方法,它表示移除或添加列、修改索引、更改数据类型或更改名称等修改。当元数据锁处于活动状态时,ALTER 也会等待应用更改。

The ALTER command provides a way to change an existing table’s structure, meaning modifications like removing or adding columns, modifying indices, changing data types, or changing names. ALTER also waits to apply changes when a metadata lock is active.

Using ALTER to Modify Columns

ALTER 与 DROP 结合使用,可以移除现有列。但是,如果该列是唯一剩余列,它将失败。

ALTER paired with DROP removes an existing column. However, it fails if the column is the only remaining column.

查看下面给出的示例 −

Review the example given below −

mysql> ALTER TABLE products_tbl DROP version_num;

使用 ALTER…​ADD 语句添加列 −

Use an ALTER…​ADD statement to add columns −

mysql> ALTER TABLE products_tbl ADD discontinued CHAR(1);

使用关键字 FIRST 和 AFTER 来指定列放置位置 −

Use the keywords FIRST and AFTER to specify placement of the column −

ALTER TABLE products_tbl ADD discontinued CHAR(1) FIRST;
ALTER TABLE products_tbl ADD discontinued CHAR(1) AFTER quantity;

请注意,关键字 FIRST 和 AFTER 仅适用于 ALTER…​ADD 语句。此外,必须删除表,然后再添加表才能重新定位。

Note the FIRST and AFTER keywords only apply to ALTER…​ADD statements. Furthermore, you must drop a table and then add it in order to reposition it.

使用 ALTER 语句中的 MODIFY 或 CHANGE 子句来更改列定义或名称。这些子句具有类似效果,但使用完全不同的语法。

Change a column definition or name by using the MODIFY or CHANGE clause in an ALTER statement. The clauses have similar effects, but utilize substantially different syntax.

请查看以下给出的 CHANGE 示例 −

Review a CHANGE example given below −

mysql> ALTER TABLE products_tbl CHANGE discontinued status CHAR(4);

在使用 CHANGE 的语句中,指定原始列,然后指定将替换它的新列。请查看以下 MODIFY 示例 −

In a statement using CHANGE, specify the original column and then the new column that will replace it. Review a MODIFY example below −

mysql> ALTER TABLE products_tbl MODIFY discontinued CHAR(4);

ALTER 命令还允许更改默认值。请查看示例 −

The ALTER command also allows for changing default values. Review an example −

mysql> ALTER TABLE products_tbl ALTER discontinued SET DEFAULT N;

还可以使用与 DROP 子句配对的方式删除默认约束 −

You can also use it to remove default constraints by pairing it with a DROP clause −

mysql> ALTER TABLE products_tbl ALTER discontinued DROP DEFAULT;

Using ALTER to Modify Tables

使用 TYPE 子句更改表类型 −

Change table type with the TYPE clause −

mysql> ALTER TABLE products_tbl TYPE = INNODB;

使用关键字 RENAME 重命名表 −

Rename a table with the RENAME keyword −

mysql> ALTER TABLE products_tbl RENAME TO products2016_tbl;