ALTER TABLEtbl_name[alter_option[,alter_option] ...] [partition_options]alter_option: {table_options| ADD [COLUMN]col_namecolumn_definition[FIRST | AFTERcol_name] | ADD [COLUMN] (col_namecolumn_definition,...) | ADD {INDEX | KEY} [index_name] [index_type] (key_part,...) [index_option] ... | ADD {FULLTEXT | SPATIAL} [INDEX | KEY] [index_name] (key_part,...) [index_option] ... | ADD [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (key_part,...) [index_option] ... | ADD [CONSTRAINT [symbol]] UNIQUE [INDEX | KEY] [index_name] [index_type] (key_part,...) [index_option] ... | ADD [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (col_name,...)reference_definition| ADD [CONSTRAINT [symbol]] CHECK (expr) [[NOT] ENFORCED] | DROP {CHECK | CONSTRAINT}symbol| ALTER {CHECK | CONSTRAINT}symbol[NOT] ENFORCED | ALGORITHM [=] {DEFAULT | INSTANT | INPLACE | COPY} | ALTER [COLUMN]col_name{ SET DEFAULT {literal| (expr)} | SET {VISIBLE | INVISIBLE} | DROP DEFAULT } | ALTER INDEXindex_name{VISIBLE | INVISIBLE} | CHANGE [COLUMN]old_col_namenew_col_namecolumn_definition[FIRST | AFTERcol_name] | [DEFAULT] CHARACTER SET [=]charset_name[COLLATE [=]collation_name] | CONVERT TO CHARACTER SETcharset_name[COLLATEcollation_name] | {DISABLE | ENABLE} KEYS | {DISCARD | IMPORT} TABLESPACE | DROP [COLUMN]col_name| DROP {INDEX | KEY}index_name| DROP PRIMARY KEY | DROP FOREIGN KEYfk_symbol| FORCE | LOCK [=] {DEFAULT | NONE | SHARED | EXCLUSIVE} | MODIFY [COLUMN]col_namecolumn_definition[FIRST | AFTERcol_name] | ORDER BYcol_name[,col_name] ... | RENAME COLUMNold_col_nameTOnew_col_name| RENAME {INDEX | KEY}old_index_nameTOnew_index_name| RENAME [TO | AS]new_tbl_name| {WITHOUT | WITH} VALIDATION }partition_options:partition_option[partition_option] ...partition_option: { ADD PARTITION (partition_definition) | DROP PARTITIONpartition_names| DISCARD PARTITION {partition_names| ALL} TABLESPACE | IMPORT PARTITION {partition_names| ALL} TABLESPACE | TRUNCATE PARTITION {partition_names| ALL} | COALESCE PARTITIONnumber| REORGANIZE PARTITIONpartition_namesINTO (partition_definitions) | EXCHANGE PARTITIONpartition_nameWITH TABLEtbl_name[{WITH | WITHOUT} VALIDATION] | ANALYZE PARTITION {partition_names| ALL} | CHECK PARTITION {partition_names| ALL} | OPTIMIZE PARTITION {partition_names| ALL} | REBUILD PARTITION {partition_names| ALL} | REPAIR PARTITION {partition_names| ALL} | REMOVE PARTITIONING }key_part: {col_name[(length)] | (expr)} [ASC | DESC]index_type: USING {BTREE | HASH}index_option: { KEY_BLOCK_SIZE [=]value|index_type| WITH PARSERparser_name| COMMENT 'string' | {VISIBLE | INVISIBLE} }table_options:table_option[[,]table_option] ...table_option: { AUTOEXTEND_SIZE [=]value| AUTO_INCREMENT [=]value| AVG_ROW_LENGTH [=]value| [DEFAULT] CHARACTER SET [=]charset_name| CHECKSUM [=] {0 | 1} | [DEFAULT] COLLATE [=]collation_name| COMMENT [=] 'string' | COMPRESSION [=] {'ZLIB' | 'LZ4' | 'NONE'} | CONNECTION [=] 'connect_string' | {DATA | INDEX} DIRECTORY [=] 'absolute path to directory' | DELAY_KEY_WRITE [=] {0 | 1} | ENCRYPTION [=] {'Y' | 'N'} | ENGINE [=]engine_name| ENGINE_ATTRIBUTE [=] 'string' | INSERT_METHOD [=] { NO | FIRST | LAST } | KEY_BLOCK_SIZE [=]value| MAX_ROWS [=]value| MIN_ROWS [=]value| PACK_KEYS [=] {0 | 1 | DEFAULT} | PASSWORD [=] 'string' | ROW_FORMAT [=] {DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT} | SECONDARY_ENGINE_ATTRIBUTE [=] 'string' | STATS_AUTO_RECALC [=] {DEFAULT | 0 | 1} | STATS_PERSISTENT [=] {DEFAULT | 0 | 1} | STATS_SAMPLE_PAGES [=]value| TABLESPACEtablespace_name[STORAGE {DISK | MEMORY}] | UNION [=] (tbl_name[,tbl_name]...) }partition_options: (seeCREATE TABLEoptions)
ALTER TABLE changes the structure of a table. ALTER TABLE更改表的结构。For example, you can add or delete columns, create or destroy indexes, change the type of existing columns, or rename columns or the table itself. 例如,您可以添加或删除列、创建或销毁索引、更改现有列的类型或重命名列或表本身。You can also change characteristics such as the storage engine used for the table or the table comment.您还可以更改特性,例如用于表或表注释的存储引擎。
To use 要使用ALTER TABLE, you need ALTER, CREATE, and INSERT privileges for the table. ALTER TABLE,您需要表的ALTER、CREATE和INSERT权限。Renaming a table requires 重命名表需要对旧表执行ALTER and DROP on the old table, ALTER, CREATE, and INSERT on the new table.ALTER和DROP操作,对新表执行ALTER、CREATE和INSERT操作。
Following the table name, specify the alterations to be made. 在表名之后,指定要进行的更改。If none are given, 如果未给出任何值,ALTER TABLE does nothing.ALTER TABLE将不执行任何操作。
The syntax for many of the permissible alterations is similar to clauses of the 许多允许的修改的语法类似于CREATE TABLE statement. CREATE TABLE语句的子句。column_definition clauses use the same syntax for ADD and CHANGE as for CREATE TABLE. column_definition子句对ADD和CHANGE使用与CREATE TABLE相同的语法。For more information, see Section 13.1.20, “CREATE TABLE Statement”.有关更多信息,请参阅第13.1.20节,“CREATE TABLE语句”。
The word 单词COLUMN is optional and can be omitted, except for RENAME COLUMN (to distinguish a column-renaming operation from the RENAME table-renaming operation).COLUMN是可选的,可以省略,但RENAME COLUMN除外(用于区分列重命名操作和表重命名操作)。
Multiple 允许在单个ADD, ALTER, DROP, and CHANGE clauses are permitted in a single ALTER TABLE statement, separated by commas. ALTER TABLE语句中使用多个ADD、ALTER、DROP和CHANGE子句,并用逗号分隔。This is a MySQL extension to standard SQL, which permits only one of each clause per 这是标准SQL的MySQL扩展,每个ALTER TABLE statement. ALTER TABLE语句只允许一个子句。For example, to drop multiple columns in a single statement, do this:例如,要在一条语句中删除多列,请执行以下操作:
ALTER TABLE t2 DROP COLUMN c, DROP COLUMN d;
If a storage engine does not support an attempted 如果存储引擎不支持尝试的ALTER TABLE operation, a warning may result. ALTER TABLE操作,则可能会导致警告。Such warnings can be displayed with 此类警告可以与SHOW WARNINGS. SHOW WARNINGS一起显示。See Section 13.7.7.42, “SHOW WARNINGS Statement”. 请参阅第13.7.7.42节,“SHOW WARNINGS语句”。For information on troubleshooting 有关ALTER TABLE, see Section B.3.6.1, “Problems with ALTER TABLE”.ALTER TABLE故障排除的信息,请参阅第B.3.6.1节,“ALTER TABLE的问题”。
For information about generated columns, see Section 13.1.9.2, “ALTER TABLE and Generated Columns”.有关生成列的信息,请参阅第13.1.9.2节,“更改表和生成列”。
For usage examples, see Section 13.1.9.3, “ALTER TABLE Examples”.有关使用示例,请参阅第13.1.9.3节,“ALTER TABLE示例”。
MySQL 8.0.17及更高版本中的InnoDB in MySQL 8.0.17 and later supports addition of multi-valued indexes on JSON columns using a key_part specification can take the form (CAST . json_path AS type ARRAY)InnoDB支持在JSON列上添加多值索引,使用key_part规范文档可以采用以下形式(将JSON_路径转换为类型数组)。See Multi-Valued Indexes, for detailed information regarding multi-valued index creation and usage of, as well as restrictions and limitations on multi-valued indexes.有关多值索引的创建和使用以及多值索引的限制和限制的详细信息,请参阅多值索引。
With the 使用C APImysql_info() C API function, you can find out how many rows were copied by ALTER TABLE. mysql_info()函数,您可以了解ALTER TABLE复制了多少行。See mysql_info().请参阅mysql_info()。
There are several additional aspects to the ALTER TABLE statement, described under the following topics in this section:ALTER TABLE语句还有几个附加方面,在本节的以下主题下进行了描述:
table_options signifies table options of the kind that can be used in the CREATE TABLE statement, such as ENGINE, AUTO_INCREMENT, AVG_ROW_LENGTH, MAX_ROWS, ROW_FORMAT, or TABLESPACE.table_options表示可以在CREATE TABLE语句中使用的表格选项,例如ENGINE、AUTO_INCREMENT、AVG_ROW_LENGTH、MAX_ROWS、ROW_FORMAT或TABLESPACE。
For descriptions of all table options, see Section 13.1.20, “CREATE TABLE Statement”. 有关所有表格选项的说明,请参阅第13.1.20节,“CREATE TABLE语句”。However, 但是,当作为表选项提供时,ALTER TABLE ignores DATA DIRECTORY and INDEX DIRECTORY when given as table options. ALTER TABLE会忽略DATA DIRECTORY和INDEX DIRECTORY。ALTER TABLE permits them only as partitioning options, and requires that you have the FILE privilege.ALTER TABLE只允许它们作为分区选项,并且要求您具有文件特权。
Use of table options with 将表格选项与ALTER TABLE provides a convenient way of altering single table characteristics. ALTER TABLE一起使用,可以方便地更改单个表格的特性。For example:例如:
If 如果t1 is currently not an InnoDB table, this statement changes its storage engine to InnoDB:t1当前不是InnoDB表,则此语句将其存储引擎更改为InnoDB:
ALTER TABLE t1 ENGINE = InnoDB;
See Section 15.6.1.5, “Converting Tables from MyISAM to InnoDB” for considerations when switching tables to the 有关将表切换到InnoDB storage engine.InnoDB存储引擎时的注意事项,请参阅第15.6.1.5节,“将表从MyISAM转换为InnoDB”。
When you specify an 指定ENGINE clause, ALTER TABLE rebuilds the table. ENGINE子句时,ALTER TABLE将重建该表。This is true even if the table already has the specified storage engine.即使该表已经具有指定的存储引擎,这也是正确的。
Running 在现有ALTER TABLE on an existing tbl_name ENGINE=INNODBInnoDB table performs a “null” ALTER TABLE operation, which can be used to defragment an InnoDB table, as described in Section 15.11.4, “Defragmenting a Table”. InnoDB表上运行LTER TABLE 将执行“tbl_name ENGINE=INNODBnull”ALTER TABLE操作,该操作可用于对InnoDB表进行碎片整理,如第15.11.4节,“对表进行碎片整理”所述。Running 在ALTER TABLE on an tbl_name FORCEInnoDB table performs the same function.InnoDB表上运行ALTER TABLE 执行相同的功能。tbl_name FORCE
ALTER TABLE and tbl_name ENGINE=INNODBALTER TABLE use online DDL. tbl_name FORCEALTER TABLE 和tbl_name ENGINE=INNODBALTER TABLE 使用在线DDL。tbl_name FORCEFor more information, see Section 15.12, “InnoDB and Online DDL”.有关更多信息,请参阅第15.12节,“InnoDB和在线DDL”。
The outcome of attempting to change the storage engine of a table is affected by whether the desired storage engine is available and the setting of the 如第5.1.11节,“服务器SQL模式”所述,尝试更改表的存储引擎的结果受所需存储引擎是否可用以及NO_ENGINE_SUBSTITUTION SQL mode, as described in Section 5.1.11, “Server SQL Modes”.NO_ENGINE_SUBSTITUTIONSQL模式设置的影响。
To prevent inadvertent loss of data, 为了防止数据意外丢失,不能使用ALTER TABLE cannot be used to change the storage engine of a table to MERGE or BLACKHOLE.ALTER TABLE将表的存储引擎更改为MERGE或BLACKHOLE。
To change the 要将InnoDB table to use compressed row-storage format:InnoDB表更改为使用压缩行存储格式,请执行以下操作:
ALTER TABLE t1 ROW_FORMAT = COMPRESSED;
The ENCRYPTION clause enables or disables page-level data encryption for an InnoDB table. ENCRYPTION子句启用或禁用InnoDB表的页面级数据加密。A keyring plugin must be installed and configured to enable encryption.必须安装并配置密钥环插件以启用加密。
If the 如果启用了table_encryption_privilege_check variable is enabled, the TABLE_ENCRYPTION_ADMIN privilege is required to use an ENCRYPTION clause with a setting that differs from the default schema encryption setting.table_encryption_privilege_check变量,则需要TABLE_ENCRYPTION_ADMIN权限才能使用具有不同于默认架构加密设置的设置的加密子句。
Prior to MySQL 8.0.16, the 在MySQL 8.0.16之前,只有在更改驻留在每个表的文件表空间中的表时,才支持ENCRYPTION clause was only supported when altering tables residing in file-per-table tablespaces. ENCRYPTION子句。As of MySQL 8.0.16, the 从MySQL 8.0.16开始,通用表空间中的表也支持ENCRYPTION clause is also supported for tables residing in general tablespaces.ENCRYPTION子句。
For tables that reside in general tablespaces, table and tablespace encryption must match.对于驻留在常规表空间中的表,表和表空间加密必须匹配。
Altering table encryption by moving a table to a different tablespace or changing the storage engine is not permitted without explicitly specifying an 在未明确指定ENCRYPTION clause.ENCRYPTION子句的情况下,不允许通过将表移动到其他表空间或更改存储引擎来更改表加密。
As of MySQL 8.0.16, specifying an 从MySQL 8.0.16开始,如果表使用不支持加密的存储引擎,则不允许使用ENCRYPTION clause with a value other than 'N' or '' is not permitted if the table uses a storage engine that does not support encryption. 'N'或''以外的值指定ENCRYPTION子句。Previously, the clause was accepted. 此前,该子句被接受。Attempting to create a table without an 也不允许尝试使用不支持加密的存储引擎在启用加密的架构中创建不带ENCRYPTION clause in an encryption-enabled schema using a storage engine that does not support encryption is also not permitted.ENCRYPTION子句的表。
For more information, see Section 15.13, “InnoDB Data-at-Rest Encryption”.有关更多信息,请参阅第15.13节,“InnoDB静态数据加密”。
To reset the current auto-increment value:要重置当前自动增量值,请执行以下操作:
ALTER TABLE t1 AUTO_INCREMENT = 13;
You cannot reset the counter to a value less than or equal to the value that is currently in use. 不能将计数器重置为小于或等于当前使用的值。For both 对于InnoDB and MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum AUTO_INCREMENT column value plus one.InnoDB和MyISAM,如果该值小于或等于当前AUTO_INCREMENT列中的最大值,则该值将重置为当前AUTO_INCREMENT列中的最大值加上一。
To change the default table character set:要更改默认表格字符集,请执行以下操作:
ALTER TABLE t1 CHARACTER SET = utf8;
See also Changing the Character Set.请参见更改字符集。
To add (or change) a table comment:要添加(或更改)表格注释,请执行以下操作:
ALTER TABLE t1 COMMENT = 'New table comment';
Use 使用ALTER TABLE with the TABLESPACE option to move InnoDB tables between existing general tablespaces, file-per-table tablespaces, and the system tablespace. ALTER TABLE配合TABLESPACE选项在现有常规表空间、每表文件表空间和系统表空间之间移动InnoDB表。See Moving Tables Between Tablespaces Using ALTER TABLE.请参见使用ALTER TABLE在表空间之间移动表。
ALTER TABLE ... TABLESPACE operations always cause a full table rebuild, even if the TABLESPACE attribute has not changed from its previous value.ALTER TABLE ... TABLESPACE操作始终会导致完整的表重建,即使TABLESPACE属性没有改变其以前的值。
ALTER TABLE ... TABLESPACE syntax does not support moving a table from a temporary tablespace to a persistent tablespace.ALTER TABLE ... TABLESPACE语法不支持将表从临时表空间移动到持久表空间。
The 受DATA DIRECTORY clause, which is supported with CREATE TABLE ... TABLESPACE, is not supported with ALTER TABLE ... TABLESPACE, and is ignored if specified.CREATE TABLE ... TABLESPACE支持的DATA DIRECTORY子句,ALTER TABLE ... TABLESPACE却不支持它,如果指定了它,则忽略它。
For more information about the capabilities and limitations of the 有关TABLESPACE option, see CREATE TABLE.TABLESPACE选项的功能和限制的更多信息,请参阅CREATE TABLE。
MySQL NDB Cluster 8.0 supports setting MySQL NDB Cluster 8.0支持设置NDB_TABLE options for controlling a table's partition balance (fragment count type), read-from-any-replica capability, full replication, or any combination of these, as part of the table comment for an ALTER TABLE statement in the same manner as for CREATE TABLE, as shown in this example:NDB_TABLE选项,以控制表的分区平衡(碎片计数类型)、从任何副本功能读取、完全复制或这些功能的任意组合,作为ALTER TABLE语句表注释的一部分,方式与CREATE TABLE相同,如本例所示:
ALTER TABLE t1 COMMENT = "NDB_TABLE=READ_BACKUP=0,PARTITION_BALANCE=FOR_RA_BY_NODE";
Bear in mind that 请记住,ALTER TABLE ... COMMENT ... discards any existing comment for the table. ALTER TABLE ... COMMENT ...放弃表的任何现有注释。See Setting NDB_TABLE options, for additional information and examples.有关更多信息和示例,请参阅设置NDB_TABLE选项。
ENGINE_ATTRIBUTE and SECONDARY_ENGINE_ATTRIBUTE options (available as of MySQL 8.0.21) are used to specify table, column, and index attributes for primary and secondary storage engines. ENGINE_ATTRIBUTE和SECONDARY_ENGINE_ATTRIBUTE选项(从MySQL 8.0.21开始提供)用于指定主存储引擎和辅助存储引擎的表、列和索引属性。The options are reserved for future use. 这些选项保留供将来使用。Index attributes cannot be altered. 无法更改索引属性。An index must be dropped and added back with the desired change, which can be performed in a single 必须删除索引,并将其添加回所需的更改,这可以在单个ALTER TABLE statement.ALTER TABLE语句中执行。
To verify that the table options were changed as intended, use 若要验证表选项是否已按预期更改,请使用SHOW CREATE TABLE, or query the INFORMATION_SCHEMA.TABLES table.SHOW CREATE TABLE或查询INFORMATION_SCHEMA.TABLES表。
使用以下算法之一处理ALTER TABLE operations are processed using one of the following algorithms:ALTER TABLE操作:
COPY: Operations are performed on a copy of the original table, and table data is copied from the original table to the new table row by row. Concurrent DML is not permitted.:对原始表的副本执行操作,并将表数据逐行从原始表复制到新表。不允许同时使用DML。
INPLACE: Operations avoid copying table data but may rebuild the table in place. :操作避免复制表数据,但可能就地重建表。An exclusive metadata lock on the table may be taken briefly during preparation and execution phases of the operation. 在操作的准备和执行阶段,可能会短暂获取表上的独占元数据锁。Typically, concurrent DML is supported.通常,支持并发DML。
INSTANT: Operations only modify metadata in the data dictionary. :操作仅修改数据字典中的元数据。No exclusive metadata locks are taken on the table during preparation and execution, and table data is unaffected, making operations instantaneous. 在准备和执行期间,表上没有独占的元数据锁,并且表数据不受影响,这使得操作是即时的。Concurrent DML is permitted. (Introduced in MySQL 8.0.12)允许并发DML。(在MySQL 8.0.12中引入)
The ALGORITHM clause is optional. ALGORITHM子句是可选的。If the 如果省略了ALGORITHM clause is omitted, MySQL uses ALGORITHM=INSTANT for storage engines and ALTER TABLE clauses that support it. ALGORITHM子句,MySQL将使用ALGORITHM=INSTANT作为存储引擎和支持它的ALTER TABLE子句。Otherwise, 否则,将使用ALGORITHM=INPLACE is used. ALGORITHM=INPLACE。If 如果不支持ALGORITHM=INPLACE is not supported, ALGORITHM=COPY is used.ALGORITHM=INPLACE,则使用ALGORITHM=COPY。
Specifying an 指定ALGORITHM clause requires the operation to use the specified algorithm for clauses and storage engines that support it, or fail with an error otherwise. ALGORITHM子句要求操作对支持它的子句和存储引擎使用指定的算法,否则操作将失败并出现错误。Specifying 指定ALGORITHM=DEFAULT is the same as omitting the ALGORITHM clause.ALGORITHM=DEFAULT与省略ALGORITHM子句相同。
使用ALTER TABLE operations that use the COPY algorithm wait for other operations that are modifying the table to complete. COPY算法的ALTER TABLE操作将等待修改表的其他操作完成。After alterations are applied to the table copy, data is copied over, the original table is deleted, and the table copy is renamed to the name of the original table. 对表副本应用更改后,将复制数据,删除原始表,并将表副本重命名为原始表的名称。While the 在执行ALTER TABLE operation executes, the original table is readable by other sessions (with the exception noted shortly). ALTER TABLE操作时,其他会话可以读取原始表(稍后会注意到异常)。Updates and writes to the table started after the 在ALTER TABLE operation begins are stalled until the new table is ready, then are automatically redirected to the new table. ALTER TABLE操作开始后启动的对表的更新和写入被暂停,直到新表准备就绪,然后自动重定向到新表。The temporary copy of the table is created in the database directory of the original table unless it is a 表的临时副本在原始表的数据库目录中创建,除非是将表移动到位于其他目录中的数据库的RENAME TO operation that moves the table to a database that resides in a different directory.RENAME TO操作。
The exception referred to earlier is that 前面提到的例外情况是,ALTER TABLE blocks reads (not just writes) at the point where it is ready to clear outdated table structures from the table and table definition caches. ALTER TABLE在准备从表和表定义缓存中清除过时的表结构时会阻止读取(而不仅仅是写入)。At this point, it must acquire an exclusive lock. 此时,它必须获得独占锁。To do so, it waits for current readers to finish, and blocks new reads and writes.为此,它等待当前读卡器完成,并阻止新的读写操作。
An 使用ALTER TABLE operation that uses the COPY algorithm prevents concurrent DML operations. COPY算法的ALTER TABLE操作可防止并发DML操作。Concurrent queries are still allowed. That is, a table-copying operation always includes at least the concurrency restrictions of 仍然允许并发查询。也就是说,表复制操作始终至少包括LOCK=SHARED (allow queries but not DML). LOCK=SHARED(允许查询,但不允许DML)的并发限制。You can further restrict concurrency for operations that support the 通过指定LOCK clause by specifying LOCK=EXCLUSIVE, which prevents DML and queries. LOCK=EXCLUSIVE,可以进一步限制支持LOCK子句的操作的并发性,这将阻止DML和查询。For more information, see Concurrency Control.有关更多信息,请参阅并发控制。
To force use of the 若要强制将COPY algorithm for an ALTER TABLE operation that would otherwise not use it, specify ALGORITHM=COPY or enable the old_alter_table system variable. COPY算法用于本来不会使用它的ALTER TABLE操作,请指定ALGORIGHT=COPY或启用系统变量old_alter_table。If there is a conflict between the 如果old_alter_table setting and an ALGORITHM clause with a value other than DEFAULT, the ALGORITHM clause takes precedence.old_alter_table设置与具有非DEFAULT的ALGORITHM子句之间存在冲突,则ALGORITHM子句优先。
For 对于InnoDB tables, an ALTER TABLE operation that uses the COPY algorithm on a table that resides in a shared tablespace can increase the amount of space used by the tablespace. InnoDB表,对驻留在共享表空间中的表使用COPY算法的ALTER TABLE操作可以增加表空间使用的空间量。Such operations require as much additional space as the data in the table plus indexes. 这样的操作需要与表中的数据加索引一样多的额外空间。For a table residing in a shared tablespace, the additional space used during the operation is not released back to the operating system as it is for a table that resides in a file-per-table tablespace.对于驻留在共享表空间中的表,操作期间使用的额外空间不会释放回操作系统,就像对于驻留在每个表空间的文件中的表一样。
For information about space requirements for online DDL operations, see Section 15.12.3, “Online DDL Space Requirements”.有关联机DDL操作的空间要求的信息,请参阅第15.12.3节,“联机DDL空间要求”。
operations that support the ALTER TABLEINPLACE algorithm include:支持INPLACE(就地)算法的ALTER TABLE操作包括:
ALTER TABLE operations supported by the InnoDB online DDL feature. InnoDB online DDL功能支持的ALTER TABLE操作。See Section 15.12.1, “Online DDL Operations”.请参阅第15.12.1节,“在线DDL操作”。
Renaming a table. 重命名表。MySQL renames files that correspond to the table MySQL重命名与表tbl_name without making a copy. tbl_name对应的文件,而不复制。(You can also use the (也可以使用RENAME TABLE statement to rename tables. RENAME TABLE语句重命名表。See Section 13.1.36, “RENAME TABLE Statement”.) 请参阅第13.1.36节,“重命名表格声明”。)Privileges granted specifically for the renamed table are not migrated to the new name. 专门为重命名的表授予的权限不会迁移到新名称。They must be changed manually.必须手动更改它们。
Operations that only modify table metadata. 仅修改表元数据的操作。These operations are immediate because the server does not touch table contents. 这些操作是即时的,因为服务器不接触表内容。Metadata-only operations include:仅元数据操作包括:
Renaming a column. 重命名列。In NDB Cluster 8.0.18 and later, this operation can also be performed online.在NDB Cluster 8.0.18及更高版本中,也可以在线执行此操作。
Changing the default value of a column (except for 更改列的默认值(NDB tables).NDB表除外)。
Modifying the definition of an 通过在有效成员值列表的末尾添加新的枚举或集合成员来修改ENUM or SET column by adding new enumeration or set members to the end of the list of valid member values, as long as the storage size of the data type does not change. ENUM或SET列的定义,只要数据类型的存储大小不变。For example, adding a member to a 例如,将一个成员添加到具有8个成员的SET column that has 8 members changes the required storage per value from 1 byte to 2 bytes; this requires a table copy. SET列中会将每个值所需的存储空间从1字节更改为2字节;这需要一个表副本。Adding members in the middle of the list causes renumbering of existing members, which requires a table copy.在列表中间添加成员会导致现有成员重新编号,这需要表复制。
Changing the definition of a spatial column to remove the 更改空间列的定义以删除SRID attribute. SRID属性。(Adding or changing an (添加或更改SRID attribute does require a rebuild and cannot be done in place because the server must verify that all values have the specified SRID value.)SRID属性确实需要重新生成,并且无法就地完成,因为服务器必须验证所有值是否具有指定的SRID值。)
As of MySQL 8.0.14, changing a column character set, when these conditions apply:从MySQL 8.0.14开始,当下列条件适用时,更改列字符集:
As of MySQL 8.0.14, changing a generated column, when these conditions apply:从MySQL 8.0.14开始,当以下条件适用时,更改生成的列:
For 对于InnoDB tables, statements that modify generated stored columns but do not change their type, expression, or nullability.InnoDB表,指修改生成的存储列但不更改其类型、表达式或可空性的语句。
For non-对于非InnoDB tables, statements that modify generated stored or virtual columns but do not change their type, expression, or nullability.InnoDB表,指修改生成的存储列或虚拟列但不更改其类型、表达式或可空性的语句。
An example of such a change is a change to the column comment.此类更改的一个示例是对列注释的更改。
Renaming an index.重命名索引。
Adding or dropping a secondary index, for 为InnoDB and NDB tables. InnoDB和NDB表添加或删除辅助索引。See Section 15.12.1, “Online DDL Operations”.请参阅第15.12.1节,“在线DDL操作”。
For 对于NDB tables, operations that add and drop indexes on variable-width columns. NDB表,在可变宽度列上添加和删除索引的操作。These operations occur online, without table copying and without blocking concurrent DML actions for most of their duration. 这些操作在线进行,没有表复制,并且在大部分时间内不会阻止并发DML操作。See Section 23.5.11, “Online Operations with ALTER TABLE in NDB Cluster”.请参阅第23.5.11节,“NDB集群中ALTER TABLE的在线操作”。
Modifying index visibility with an 使用ALTER INDEX operation.ALTER INDEX操作修改索引可见性。
Column modifications of tables containing generated columns that depend on columns with a 如果生成的列表达式中不涉及修改的列,则对包含生成的列的表进行列修改,这些列依赖于具有DEFAULT value if the modified columns are not involved in the generated column expressions. DEFAULT值的列。For example, changing the 例如,可以就地更改单独列的NULL property of a separate column can be done in place without a table rebuild.NULL属性,而无需重新生成表。
支持ALTER TABLE operations that support the INSTANT algorithm include:INSTANT(即时)算法的ALTER TABLE操作包括:
Adding a column. 添加一列。This feature is referred to as “Instant 此功能称为“即时添加列”。ADD COLUMN”. Limitations apply. 限制适用。See Section 15.12.1, “Online DDL Operations”.请参阅第15.12.1节,“在线DDL操作”。
Adding or dropping a virtual column.添加或删除虚拟列。
Adding or dropping a column default value.添加或删除列默认值。
Modifying the definition of an 修改ENUM or SET column. ENUM列或SET列的定义。The same restrictions apply as described above for 上述相同的限制适用于ALGORITHM=INSTANT.ALGORITHM=INSTANT。
Changing the index type.更改索引类型。
Renaming a table. 重命名表。The same restrictions apply as described above for 上述相同的限制适用于ALGORITHM=INSTANT.ALGORITHM=INSTANT。
For more information about operations that support 有关支持ALGORITHM=INSTANT, see Section 15.12.1, “Online DDL Operations”.ALGORITHM=INSTANT的操作的更多信息,请参阅第15.12.1节,“在线DDL操作”。
ALTER TABLE upgrades MySQL 5.5 temporal columns to 5.6 format for ADD COLUMN, CHANGE COLUMN, MODIFY COLUMN, ADD INDEX, and FORCE operations. ALTER TABLE将MySQL 5.5临时列升级为5.6格式,用于ADD COLUMN、CHANGE COLUMN、MODIFY COLUMN、ADD INDEX和FORCE操作。This conversion cannot be done using the 无法使用INPLACE algorithm because the table must be rebuilt, so specifying ALGORITHM=INPLACE in these cases results in an error. INPLACE算法完成此转换,因为必须重新生成表,因此在这些情况下指定ALGORITHM=INPLACE会导致错误。Specify 如有必要,指定ALGORITHM=COPY if necessary.ALGORITHM=COPY。
If an 如果用于按ALTER TABLE operation on a multicolumn index used to partition a table by KEY changes the order of the columns, it can only be performed using ALGORITHM=COPY.KEY对表进行分区的多列索引上的ALTER TABLE操作更改了列的顺序,则只能使用ALGORITHM=COPY来执行该操作。
The WITHOUT VALIDATION and WITH VALIDATION clauses affect whether ALTER TABLE performs an in-place operation for virtual generated column modifications. WITH VALIDATION和WITH VALIDATION子句影响ALTER TABLE是否对虚拟生成的列修改执行就地操作。See Section 13.1.9.2, “ALTER TABLE and Generated Columns”.请参阅第13.1.9.2节,“更改表格和生成的列”。
NDB Cluster 8.0 supports online operations using the same NDB Cluster 8.0支持使用与标准MySQL服务器相同的ALGORITHM=INPLACE syntax used with the standard MySQL Server. ALGORITHM=INPLACE语法进行在线操作。NDB does not support changing a tablespace online; beginning with NDB 8.0.21, it is disallowed. NDB不支持在线更改表空间;从NDB 8.0.21开始,它是不允许的。See Section 23.5.11, “Online Operations with ALTER TABLE in NDB Cluster”, for more information.更多信息,请参阅第23.5.11节,“NDB集群中ALTER TABLE的在线操作”。
ALTER TABLE with DISCARD ... PARTITION ... TABLESPACE or IMPORT ... PARTITION ... TABLESPACE does not create any temporary tables or temporary partition files.ALTER TABLE与DISCARD ... PARTITION ... TABLESPACE或IMPORT ... PARTITION ... TABLESPACE不创建任何临时表或临时分区文件。
使用ALTER TABLE with ADD PARTITION, DROP PARTITION, COALESCE PARTITION, REBUILD PARTITION, or REORGANIZE PARTITION does not create temporary tables (except when used with NDB tables); however, these operations can and do create temporary partition files.ADD PARTITION(添加分区)、DROP PARTITION(删除)、COALESCE PARTITION(合并分区)、REBUILD PARTITION(重建分区)或REORGANIZE PARTITION(重新组织分区)的ALTER TABLE不会创建临时表(与NDB表一起使用时除外);但是,这些操作可以并且确实创建临时分区文件。
ADD or DROP operations for RANGE or LIST partitions are immediate operations or nearly so. RANGE分区或LIST分区的ADD或DROP操作是即时操作,或者几乎是即时操作。除非使用ADD or COALESCE operations for HASH or KEY partitions copy data between all partitions, unless LINEAR HASH or LINEAR KEY was used; this is effectively the same as creating a new table, although the ADD or COALESCE operation is performed partition by partition. LINEAR HASH或LINEAR KEY,否则HASH或KEY分区的ADD(添加)或COALESCE合并操作会在所有分区之间复制数据;这实际上与创建新表相同,尽管添加或合并操作是逐分区执行的。REORGANIZE operations copy only changed partitions and do not touch unchanged ones.REORGANIZE操作只复制已更改的分区,不接触未更改的分区。
For 对于MyISAM tables, you can speed up index re-creation (the slowest part of the alteration process) by setting the myisam_sort_buffer_size system variable to a high value.MyISAM表,通过将系统变量myisam_sort_buffer_size设置为高值,可以加快索引的重新创建(更改过程中最慢的部分)。
For 对于支持它的ALTER TABLE operations that support it, you can use the LOCK clause to control the level of concurrent reads and writes on a table while it is being altered. ALTER TABLE操作,您可以使用LOCK子句在表被更改时控制表上并发读写的级别。Specifying a non-default value for this clause enables you to require a certain amount of concurrent access or exclusivity during the alter operation, and halts the operation if the requested degree of locking is not available.为此子句指定非默认值使您能够在alter操作期间要求一定量的并发访问或独占性,并在请求的锁定程度不可用时停止操作。
Only 对于使用LOCK = DEFAULT is permitted for operations that use ALGORITHM=INSTANT. ALGORITHM=INSTANT的操作,只允许LOCK = DEFAULT。The other 其他LOCK clause parameters are not applicable.LOCK子句参数不适用。
The parameters for the LOCK clause are:LOCK子句的参数为:
LOCK = DEFAULT
Maximum level of concurrency for the given 给定ALGORITHM clause (if any) and ALTER TABLE operation: Permit concurrent reads and writes if supported. ALGORITHM子句(如果有)和ALTER TABLE操作的最大并发级别:允许并发读写(如果支持)。If not, permit concurrent reads if supported. 如果不支持,则允许并发读取(如果支持)。If not, enforce exclusive access.如果不是,则强制执行独占访问。
LOCK = NONE
If supported, permit concurrent reads and writes. Otherwise, an error occurs.如果支持,则允许并发读写。否则,将发生错误。
LOCK = SHARED
If supported, permit concurrent reads but block writes. 如果支持,则允许并发读取,但不允许块写入。Writes are blocked even if concurrent writes are supported by the storage engine for the given 即使存储引擎支持给定ALGORITHM clause (if any) and ALTER TABLE operation. ALGORITHM子句(如果有)和ALTER TABLE操作的并发写入,也会阻止写入。If concurrent reads are not supported, an error occurs.如果不支持并发读取,则会发生错误。
LOCK = EXCLUSIVE
Enforce exclusive access. 强制独占访问。This is done even if concurrent reads/writes are supported by the storage engine for the given 即使存储引擎支持给定ALGORITHM clause (if any) and ALTER TABLE operation.ALGORITHM子句(如果有)和ALTER TABLE操作的并发读/写,也可以执行此操作。
Use 使用ADD to add new columns to a table, and DROP to remove existing columns. ADD向表中添加新列,使用DROP删除现有列。DROP is a MySQL extension to standard SQL.col_nameDROP 是标准SQL的MySQL扩展。col_name
To add a column at a specific position within a table row, use 要在表格行中的特定位置添加列,请使用FIRST or AFTER . col_nameFIRST或AFTER 名称。col_nameThe default is to add the column last.默认设置为在最后面添加列。
If a table contains only one column, the column cannot be dropped. 如果表仅包含一列,则无法删除该列。If what you intend is to remove the table, use the 如果要删除该表,请改用DROP TABLE statement instead.DROP TABLE语句。
If columns are dropped from a table, the columns are also removed from any index of which they are a part. 如果从表中删除列,则这些列也将从它们所属的任何索引中删除。If all columns that make up an index are dropped, the index is dropped as well. 如果删除了构成索引的所有列,则该索引也将被删除。If you use 如果使用CHANGE or MODIFY to shorten a column for which an index exists on the column, and the resulting column length is less than the index length, MySQL shortens the index automatically.CHANGE或MODIFY来缩短列上存在索引的列,并且得到的列长度小于索引长度,MySQL会自动缩短索引。
For 对于ALTER TABLE ... ADD, if the column has an expression default value that uses a nondeterministic function, the statement may produce a warning or error. ALTER TABLE ... ADD,如果列具有使用不确定函数的表达式默认值,则该语句可能会产生警告或错误。For further information, see Section 11.6, “Data Type Default Values”, and Section 17.1.3.7, “Restrictions on Replication with GTIDs”.有关更多信息,请参阅第11.6节,“数据类型默认值”和第17.1.3.7节,“使用GTID复制的限制”。
The CHANGE, MODIFY, RENAME COLUMN, and ALTER clauses enable the names and definitions of existing columns to be altered. CHANGE、MODIFY、RENAME COLUMN和ALTER子句允许更改现有列的名称和定义。They have these comparative characteristics:它们具有以下比较特征:
CHANGE:
Can rename a column and change its definition, or both.可以重命名列并更改其定义,或同时更改两者。
Has more capability than 具有比MODIFY or RENAME COLUMN, but at the expense of convenience for some operations. MODIFY或RENAME COLUMN更大的功能,但以牺牲某些操作的便利性为代价。如果不重命名列,则CHANGE requires naming the column twice if not renaming it, and requires respecifying the column definition if only renaming it.CHANGE需要对其命名两次;如果仅重命名列,则需要重新指定列定义。
With 使用FIRST or AFTER, can reorder columns.FIRST或AFTER,可以对列重新排序。
MODIFY:
Can change a column definition but not its name.可以更改列定义,但不能更改其名称。
More convenient than 比CHANGE to change a column definition without renaming it.CHANGE更方便,无需重命名即可更改列定义。
With 使用FIRST or AFTER, can reorder columns.FIRST或AFTER,可以对列重新排序。
RENAME COLUMN:
Can change a column name but not its definition.可以更改列名,但不能更改其定义。
More convenient than 重命名列而不CHANGE to rename a column without changing its definition.CHANGE其定义比更改更方便。
ALTER: Used only to change a column default value.:仅用于更改列的默认值。
CHANGE is a MySQL extension to standard SQL. CHANGE是对标准SQL的MySQL扩展。MODIFY and RENAME COLUMN are MySQL extensions for Oracle compatibility.MODIFY和RENAME COLUMN是用于Oracle兼容性的MySQL扩展。
To alter a column to change both its name and definition, use 要更改列以同时更改其名称和定义,请使用CHANGE, specifying the old and new names and the new definition. CHANGE,指定新旧名称和新定义。For example, to rename an 例如,要将INT NOT NULL column from a to b and change its definition to use the BIGINT data type while retaining the NOT NULL attribute, do this:INT NOT NULL列从a重命名为b,并将其定义更改为使用BIGINT数据类型,同时保留NOT NULL属性,请执行以下操作:
ALTER TABLE t1 CHANGE a b BIGINT NOT NULL;
To change a column definition but not its name, use 要更改列定义但不更改其名称,请使用CHANGE or MODIFY. CHANGE或MODIFY。With 使用CHANGE, the syntax requires two column names, so you must specify the same name twice to leave the name unchanged. CHANGE时,语法需要两个列名,因此必须指定两次相同的名称才能保持名称不变。For example, to change the definition of column 例如,要更改列b, do this:b的定义,请执行以下操作:
ALTER TABLE t1 CHANGE b b INT NOT NULL;
MODIFY is more convenient to change the definition without changing the name because it requires the column name only once:MODIFY在不更改名称的情况下更改定义更方便,因为它只需要一次列名:
ALTER TABLE t1 MODIFY b INT NOT NULL;
To change a column name but not its definition, use 若要更改列名但不更改其定义,请使用CHANGE or RENAME COLUMN. CHANGE或RENAME COLUMN。With 使用CHANGE, the syntax requires a column definition, so to leave the definition unchanged, you must respecify the definition the column currently has. CHANGE时,语法需要一个列定义,因此要保持该定义不变,必须重新指定该列当前的定义。For example, to rename an 例如,要将INT NOT NULL column from b to a, do this:INT NOT NULL列从b重命名为a,请执行以下操作:
ALTER TABLE t1 CHANGE b a INT NOT NULL;
RENAME COLUMN is more convenient to change the name without changing the definition because it requires only the old and new names:RENAME COLUMN在不更改定义的情况下更改名称更方便,因为它只需要旧名称和新名称:
ALTER TABLE t1 RENAME COLUMN b TO a;
In general, you cannot rename a column to a name that already exists in the table. 通常,不能将列重命名为表中已存在的名称。However, this is sometimes not the case, such as when you swap names or move them through a cycle. 但是,有时情况并非如此,例如交换名称或在循环中移动名称时。If a table has columns named 如果表包含名为a, b, and c, these are valid operations:a、b和c的列,则这些是有效的操作:
-- swap a and b
ALTER TABLE t1 RENAME COLUMN a TO b,
RENAME COLUMN b TO a;
-- "rotate" a, b, c through a cycle
ALTER TABLE t1 RENAME COLUMN a TO b,
RENAME COLUMN b TO c,
RENAME COLUMN c TO a;
For column definition changes using 对于使用CHANGE or MODIFY, the definition must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. CHANGE或MODIFY进行的列定义更改,定义必须包括数据类型和应应用于新列的所有属性,而不是索引属性(如主键或唯一)。Attributes present in the original definition but not specified for the new definition are not carried forward. 原始定义中存在但未为新定义指定的属性不会结转。Suppose that a column 假设列col1 is defined as INT UNSIGNED DEFAULT 1 COMMENT 'my column' and you modify the column as follows, intending to change only INT to BIGINT:col1被定义为INT UNSIGNED DEFAULT 1 COMMENT 'my column',您对该列进行如下修改,打算仅将INT更改为BIGINT:
ALTER TABLE t1 MODIFY col1 BIGINT;
That statement changes the data type from 该语句将数据类型从INT to BIGINT, but it also drops the UNSIGNED, DEFAULT, and COMMENT attributes. INT更改为BIGINT,但也会删除UNSIGNED、DEFAULT和COMMENT属性。To retain them, the statement must include them explicitly:要保留它们,语句必须明确包含它们:
ALTER TABLE t1 MODIFY col1 BIGINT UNSIGNED DEFAULT 1 COMMENT 'my column';
For data type changes using 对于使用CHANGE or MODIFY, MySQL tries to convert existing column values to the new type as well as possible.CHANGE或MODIFY进行的数据类型更改,MySQL会尽可能地将现有列值转换为新类型。
This conversion may result in alteration of data. 此转换可能导致数据的更改。For example, if you shorten a string column, values may be truncated. 例如,如果缩短字符串列,值可能会被截断。To prevent the operation from succeeding if conversions to the new data type would result in loss of data, enable strict SQL mode before using 如果转换为新数据类型会导致数据丢失,为了防止操作成功,请在使用ALTER TABLE (see Section 5.1.11, “Server SQL Modes”).ALTER TABLE之前启用严格的SQL模式(请参阅第5.1.11节,“服务器SQL模式”)。
If you use 如果使用CHANGE or MODIFY to shorten a column for which an index exists on the column, and the resulting column length is less than the index length, MySQL shortens the index automatically.CHANGE或MODIFY来缩短列上存在索引的列,并且得到的列长度小于索引长度,MySQL会自动缩短索引。
For columns renamed by 对于通过CHANGE or RENAME COLUMN, MySQL automatically renames these references to the renamed column:CHANGE或RENAME COLUMN重命名的列,MySQL会自动将这些引用重命名为重命名列:
Indexes that refer to the old column, including invisible indexes and disabled 引用旧列的索引,包括不可见索引和禁用的MyISAM indexes.MyISAM索引。
Foreign keys that refer to the old column.引用旧列的外键。
For columns renamed by 对于通过CHANGE or RENAME COLUMN, MySQL does not automatically rename these references to the renamed column:CHANGE或RENAME COLUMN重命名的列,MySQL不会自动将这些引用重命名为重命名列:
Generated column and partition expressions that refer to the renamed column. 生成的列和分区表达式引用重命名的列。You must use 必须使用CHANGE to redefine such expressions in the same ALTER TABLE statement as the one that renames the column.CHANGE在与重命名列的语句相同的ALTER TABLE语句中重新定义此类表达式。
Views and stored programs that refer to the renamed column. You must manually alter the definition of these objects to refer to the new column name.引用重命名列的视图和存储程序。必须手动更改这些对象的定义以引用新列名。
To reorder columns within a table, use 若要对表中的列重新排序,请在FIRST and AFTER in CHANGE or MODIFY operations.CHANGE或MODIFY操作中使用FIRST和LAST。
ALTER ... SET DEFAULT or ALTER ... DROP DEFAULT specify a new default value for a column or remove the old default value, respectively. ALTER ... SET DEFAULT或ALTER ... DROP DEFAULT分别为列指定新的默认值或删除旧的默认值。If the old default is removed and the column can be 如果删除了旧的默认值,并且列可以为NULL, the new default is NULL. NULL,则新的默认值为NULL。If the column cannot be 如果列不能为NULL, MySQL assigns a default value as described in Section 11.6, “Data Type Default Values”.NULL,MySQL将按照第11.6节,“数据类型默认值”中的说明分配一个默认值。
As of MySQL 8.0.23, 从MySQL 8.0.23开始,ALTER ... SET VISIBLE and ALTER ... SET INVISIBLE enable column visibility to be changed. ALTER ... SET VISIBLE和ALTER ... SET INVISIBLE使列可见性可以更改。See Section 13.1.20.10, “Invisible Columns”.请参阅第13.1.20.10节,“隐形列”。
DROP PRIMARY KEY drops the primary key. DROP PRIMARY KEY删除主键。If there is no primary key, an error occurs. 如果没有主键,则会发生错误。For information about the performance characteristics of primary keys, especially for 有关主键(尤其是InnoDB tables, see Section 8.3.2, “Primary Key Optimization”.InnoDB表)性能特征的信息,请参阅第8.3.2节,“主键优化”。
If the 如果启用了系统变量sql_require_primary_key system variable is enabled, attempting to drop a primary key produces an error.sql_require_primary_key,则尝试删除主键会产生错误。
If you add a 如果向表中添加UNIQUE INDEX or PRIMARY KEY to a table, MySQL stores it before any nonunique index to permit detection of duplicate keys as early as possible.UNIQUE INDEX或PRIMARY KEY,MySQL会将其存储在任何非唯一索引之前,以允许尽早检测重复键。
DROP INDEX removes an index. DROP INDEX删除索引。This is a MySQL extension to standard SQL. 这是标准SQL的MySQL扩展。See Section 13.1.27, “DROP INDEX Statement”. 请参阅第13.1.27节,“DROP INDEX语句”。To determine index names, use 要确定索引名称,请使用SHOW INDEX FROM .tbl_nameSHOW INDEX FROM 。tbl_name
Some storage engines permit you to specify an index type when creating an index. 某些存储引擎允许您在创建索引时指定索引类型。The syntax for the index_type specifier is USING . type_nameindex_type说明符的语法是USING 。type_nameFor details about 有关USING, see Section 13.1.15, “CREATE INDEX Statement”. USING的详细信息,请参阅第13.1.15节,“CREATE INDEX语句”。The preferred position is after the column list. 首选位置在列列表之后。Expect support for use of the option before the column list to be removed in a future MySQL release.在将来的MySQL版本中删除列列表之前,希望支持使用该选项。
index_option values specify additional options for an index. index_option值指定索引的其他选项。USING is one such option. USING是一种选择。For details about permissible 有关允许index_option values, see Section 13.1.15, “CREATE INDEX Statement”.index_option值的详细信息,请参阅第13.1.15节,“CREATE INDEX语句”。
RENAME INDEX renames an index. old_index_name TO new_index_nameThis is a MySQL extension to standard SQL. 这是标准SQL的MySQL扩展。The content of the table remains unchanged. 该表的内容保持不变。old_index_name must be the name of an existing index in the table that is not dropped by the same ALTER TABLE statement. old_index_name必须是表中未被同一ALTER TABLE语句删除的现有索引的名称。new_index_name is the new index name, which cannot duplicate the name of an index in the resulting table after changes have been applied. new_index_name是新的索引名称,在应用更改后,它不能与结果表中的索引名称重复。Neither index name can be 两个索引名都不能是PRIMARY.PRIMARY。
If you use 如果在ALTER TABLE on a MyISAM table, all nonunique indexes are created in a separate batch (as for REPAIR TABLE). MyISAM表上使用ALTER TABLE,则所有非唯一索引都将在单独的批处理中创建(与REPAIR TABLE一样)。This should make 当您有许多索引时,这将使ALTER TABLE much faster when you have many indexes.ALTER TABLE更快。
For 对于MyISAM tables, key updating can be controlled explicitly. MyISAM表,可以显式控制密钥更新。Use 使用ALTER TABLE ... DISABLE KEYS to tell MySQL to stop updating nonunique indexes. ALTER TABLE ... DISABLE KEYS以通知MySQL停止更新非唯一索引。Then use 然后使用ALTER TABLE ... ENABLE KEYS to re-create missing indexes. ALTER TABLE ... ENABLE KEYS以重新创建缺少的索引。MyISAM does this with a special algorithm that is much faster than inserting keys one by one, so disabling keys before performing bulk insert operations should give a considerable speedup. MyISAM使用一种比逐个插入密钥快得多的特殊算法来实现这一点,因此在执行批量插入操作之前禁用密钥应该会带来相当大的加速。Using 使用ALTER TABLE ... DISABLE KEYS requires the INDEX privilege in addition to the privileges mentioned earlier.ALTER TABLE ... DISABLE KEYS除了前面提到的权限外,还需要INDEX权限。
While the nonunique indexes are disabled, they are ignored for statements such as 虽然禁用了非唯一索引,但对于SELECT and EXPLAIN that otherwise would use them.SELECT和EXPLAIN等语句,它们将被忽略,否则将使用它们。
After an 在ALTER TABLE statement, it may be necessary to run ANALYZE TABLE to update index cardinality information. ALTER TABLE语句之后,可能需要运行ANALYZE TABLE来更新索引基数信息。See Section 13.7.7.22, “SHOW INDEX Statement”.请参阅第13.7.7.22节,“SHOW INDEX语句”。
The ALTER INDEX operation permits an index to be made visible or invisible. ALTER INDEX操作允许使索引可见或不可见。An invisible index is not used by the optimizer. 优化器不使用不可见索引。Modification of index visibility applies to indexes other than primary keys (either explicit or implicit). 索引可见性的修改适用于主键以外的索引(显式或隐式)。This feature is storage engine neutral (supported for any engine). 此功能为存储引擎空档(支持任何引擎)。For more information, see Section 8.3.12, “Invisible Indexes”.有关更多信息,请参阅第8.3.12节,“不可见索引”。
The FOREIGN KEY and REFERENCES clauses are supported by the InnoDB and NDB storage engines, which implement ADD [CONSTRAINT [. symbol]] FOREIGN KEY [index_name] (...) REFERENCES ... (...)InnoDB和NDB存储引擎支持FOREIGN KEY(外键)子句和REFERENCES子句,它们实现了ADD [CONSTRAINT [。symbol]] FOREIGN KEY [index_name] (...) REFERENCES ... (...)See Section 13.1.20.5, “FOREIGN KEY Constraints”. 请参阅第13.1.20.5节,“外键约束”。For other storage engines, the clauses are parsed but ignored.对于其他存储引擎,这些子句将被解析但忽略。
For 对于ALTER TABLE, unlike CREATE TABLE, ADD FOREIGN KEY ignores index_name if given and uses an automatically generated foreign key name. ALTER TABLE,与CREATE TABLE不同,ADD FOREIGN KEY会忽略给定的index_name,并使用自动生成的外键名称。As a workaround, include the 作为一种解决方法,包括CONSTRAINT clause to specify the foreign key name:CONSTRAINT子句以指定外键名称:
ADD CONSTRAINT name FOREIGN KEY (....) ...
MySQL silently ignores inline MySQL默认忽略内联REFERENCES specifications, where the references are defined as part of the column specification. REFERENCES规范,其中引用被定义为列规范的一部分。MySQL accepts only MySQL只接受定义为分开的REFERENCES clauses defined as part of a separate FOREIGN KEY specification.FOREIGN KEY规范文档一部分的REFERENCES子句。
Partitioned 分区的InnoDB tables do not support foreign keys. InnoDB表不支持外键。This restriction does not apply to 此限制不适用于NDB tables, including those explicitly partitioned by [LINEAR] KEY. NDB表,包括那些由[LINEAR] KEY显式分区的表。For more information, see Section 24.6.2, “Partitioning Limitations Relating to Storage Engines”.有关更多信息,请参阅第24.6.2节,“与存储引擎相关的分区限制”。
MySQL Server and NDB Cluster both support the use of MySQL服务器和NDB集群都支持使用ALTER TABLE to drop foreign keys:ALTER TABLE删除外键:
ALTER TABLEtbl_nameDROP FOREIGN KEYfk_symbol;
Adding and dropping a foreign key in the same ALTER TABLE statement is supported for ALTER TABLE ... ALGORITHM=INPLACE but not for ALTER TABLE ... ALGORITHM=COPY.ALTER TABLE ... ALGORITHM=INPLACE支持在同一ALTER TABLE语句中添加和删除外键,但ALTER TABLE ... ALGORITHM=COPY不支持这么做。
The server prohibits changes to foreign key columns that have the potential to cause loss of referential integrity. 服务器禁止更改可能导致引用完整性丢失的外键列。A workaround is to use 解决方法是在更改列定义之前使用ALTER TABLE ... DROP FOREIGN KEY before changing the column definition and ALTER TABLE ... ADD FOREIGN KEY afterward. ALTER TABLE ... DROP FOREIGN KEY,然后使用ALTER TABLE ... ADD FOREIGN KEY。Examples of prohibited changes include:禁止更改的示例包括:
Changes to the data type of foreign key columns that may be unsafe. 对外键列数据类型的更改可能不安全。For example, changing 例如,允许将VARCHAR(20) to VARCHAR(30) is permitted, but changing it to VARCHAR(1024) is not because that alters the number of length bytes required to store individual values.VARCHAR(20)更改为VARCHAR(30),但不允许将其更改为VARCHAR(1024),因为这会改变存储单个值所需的长度字节数。
Changing a 禁止在非严格模式下将NULL column to NOT NULL in non-strict mode is prohibited to prevent converting NULL values to default non-NULL values, for which there are no corresponding values in the referenced table. NULL列更改为NOT NULL,以防止将NULL值转换为默认的非NULL值,因为引用的表中没有相应的值。The operation is permitted in strict mode, but an error is returned if any such conversion is required.在严格模式下允许该操作,但如果需要任何此类转换,将返回错误。
ALTER TABLE changes internally generated foreign key constraint names and user-defined foreign key constraint names that begin with the string “tbl_name RENAME new_tbl_nametbl_name_ibfk_” to reflect the new table name. ALTER TABLE 更改内部生成的外键约束名称和用户定义的外键约束名称(以字符串“tbl_name RENAME new_tbl_nametbl_name_ibfk_”开头),以反映新表名称。InnoDB interprets foreign key constraint names that begin with the string “tbl_name_ibfk_” as internally generated names.InnoDB将以字符串“tbl_name_ibfk_”开头的外键约束名称解释为内部生成的名称。
Prior to MySQL 8.0.16, 在MySQL 8.0.16之前,ALTER TABLE permits only the following limited version of CHECK constraint-adding syntax, which is parsed and ignored:ALTER TABLE只允许以下有限版本的CHECK约束添加语法,该语法被解析并忽略:
ADD CHECK (expr)
As of MySQL 8.0.16, 从MySQL 8.0.16开始,ALTER TABLE permits CHECK constraints for existing tables to be added, dropped, or altered:ALTER TABLE允许添加、删除或更改现有表的CHECK约束:
Add a new 添加新的CHECK constraint:CHECK约束:
ALTER TABLEtbl_nameADD CONSTRAINT [symbol] CHECK (expr) [[NOT] ENFORCED];
The meaning of constraint syntax elements is the same as for 约束语法元素的含义与CREATE TABLE. CREATE TABLE相同。See Section 13.1.20.6, “CHECK Constraints”.请参阅第13.1.20.6节,“检查约束”。
Drop an existing 删除名为CHECK constraint named symbol:symbol的现有CHECK约束:
ALTER TABLEtbl_nameDROP CHECKsymbol;
Alter whether an existing 更改是否强制执行名为CHECK constraint named symbol is enforced:symbol的现有CHECK约束:
ALTER TABLEtbl_nameALTER CHECKsymbol[NOT] ENFORCED;
The DROP CHECK and ALTER CHECK clauses are MySQL extensions to standard SQL.DROP CHECK和ALTER CHECK子句是标准SQL的MySQL扩展。
As of MySQL 8.0.19, 从MySQL 8.0.19开始,ALTER TABLE permits more general (and SQL standard) syntax for dropping and altering existing constraints of any type, where the constraint type is determined from the constraint name:ALTER TABLE允许使用更通用(和SQL标准)的语法删除和更改任何类型的现有约束,其中约束类型由约束名称确定:
Drop an existing constraint named 删除名为symbol:symbol的现有约束:
ALTER TABLEtbl_nameDROP CONSTRAINTsymbol;
If the 如果启用了系统变量sql_require_primary_key system variable is enabled, attempting to drop a primary key produces an error.sql_require_primary_key,则尝试删除主键会产生错误。
Alter whether an existing constraint named 更改是否强制实施名为symbol is enforced:symbol的现有约束:
ALTER TABLEtbl_nameALTER CONSTRAINTsymbol[NOT] ENFORCED;
Only 只有CHECK constraints can be altered to be unenforced. CHECK约束可以更改为非强制。All other constraint types are always enforced.所有其他约束类型始终是强制的。
The SQL standard specifies that all types of constraints (primary key, unique index, foreign key, check) belong to the same namespace. SQL标准指定所有类型的约束(主键、唯一索引、外键、检查)都属于同一名称空间。In MySQL, each constraint type has its own namespace per schema. 在MySQL中,每个约束类型在每个模式中都有自己的名称空间。Consequently, names for each type of constraint must be unique per schema, but constraints of different types can have the same name. 因此,每种类型的约束的名称在每个模式中都必须是唯一的,但不同类型的约束可以具有相同的名称。When multiple constraints have the same name, 当多个约束具有相同名称时,DROP CONSTRAINT and ADD CONSTRAINT are ambiguous and an error occurs. DROP CONSTRAINT和ADD CONSTRAINT将不明确,并发生错误。In such cases, constraint-specific syntax must be used to modify the constraint. 在这种情况下,必须使用特定于约束的语法来修改约束。For example, use 例如,使用DROP PRIMARY KEY or DROP FOREIGN KEY to drop a primary key or foreign key.DROP PRIMARY KEY或DROP FOREIGN KEY来删除主键或外键。
If a table alteration causes a violation of an enforced 如果表更改导致违反强制CHECK constraint, an error occurs and the table is not modified. CHECK约束,则会发生错误,并且不会修改该表。Examples of operations for which an error occurs:发生错误的操作示例:
Attempts to add the 尝试将AUTO_INCREMENT attribute to a column that is used in a CHECK constraint.AUTO_INCREMENT属性添加到CHECK约束中使用的列。
Attempts to add an enforced 尝试添加强制CHECK constraint or enforce a nonenforced CHECK constraint for which existing rows violate the constraint condition.CHECK约束或强制现有行违反约束条件的非强制CHECK约束。
Attempts to modify, rename, or drop a column that is used in a 尝试修改、重命名或删除CHECK constraint, unless that constraint is also dropped in the same statement. CHECK约束中使用的列,除非该约束也在同一语句中删除。Exception: If a 例外:如果CHECK constraint refers only to a single column, dropping the column automatically drops the constraint.CHECK约束仅指单个列,则删除该列将自动删除该约束。
ALTER TABLE changes internally generated and user-defined tbl_name RENAME new_tbl_nameCHECK constraint names that begin with the string “tbl_name_chk_” to reflect the new table name. ALTER TABLE 更改内部生成的tbl_name RENAME new_tbl_nameCHECK约束名称和用户定义的CHECK约束名称(以字符串“tbl_name_chk_”开头),以反映新表名称。MySQL interprets MySQL将以字符串“CHECK constraint names that begin with the string “tbl_name_chk_” as internally generated names.tbl_name_chk_”开头的检查约束名称解释为内部生成的名称。
To change the table default character set and all character columns (要将表格默认字符集和所有字符列(CHAR, VARCHAR, TEXT) to a new character set, use a statement like this:CHAR、VARCHAR、TEXT)更改为新的字符集,请使用如下语句:
ALTER TABLEtbl_nameCONVERT TO CHARACTER SETcharset_name;
The statement also changes the collation of all character columns. 该语句还更改所有字符列的排序规则。If you specify no 如果未指定COLLATE clause to indicate which collation to use, the statement uses default collation for the character set. COLLATE子句来指示要使用的排序规则,则语句将使用字符集的默认排序规则。If this collation is inappropriate for the intended table use (for example, if it would change from a case-sensitive collation to a case-insensitive collation), specify a collation explicitly.如果此排序规则不适合预期的表用途(例如,如果它将从区分大小写的排序规则更改为不区分大小写的排序规则),请显式指定排序规则。
For a column that has a data type of 对于数据类型为VARCHAR or one of the TEXT types, CONVERT TO CHARACTER SET changes the data type as necessary to ensure that the new column is long enough to store as many characters as the original column. VARCHAR或其中一种TEXT类型的列,CONVERT TO CHARACTER SET会根据需要更改数据类型,以确保新列的长度足以存储与原始列相同数量的字符。For example, a 例如,TEXT column has two length bytes, which store the byte-length of values in the column, up to a maximum of 65,535. TEXT列有两个长度字节,用于存储列中值的字节长度,上限为65535。For a 对于latin1 TEXT column, each character requires a single byte, so the column can store up to 65,535 characters. latin1文本列,每个字符需要一个字节,因此该列最多可以存储65535个字符。If the column is converted to 如果将列转换为utf8, each character might require up to three bytes, for a maximum possible length of 3 × 65,535 = 196,605 bytes. utf8,则每个字符可能需要最多三个字节,最大可能长度为365535=196605字节。That length does not fit in a 该长度不适合TEXT column's length bytes, so MySQL converts the data type to MEDIUMTEXT, which is the smallest string type for which the length bytes can record a value of 196,605. TEXT列的长度字节,因此MySQL将数据类型转换为MEDIUMTEXT,这是长度字节可以记录值为196,605的最小字符串类型。Similarly, a 类似地,VARCHAR column might be converted to MEDIUMTEXT.VARCHAR列可能会转换为MEDIUMTEXT。
To avoid data type changes of the type just described, do not use 若要避免对刚才描述的类型进行数据类型更改,请不要使用CONVERT TO CHARACTER SET. CONVERT TO CHARACTER SET。Instead, use 相反,请使用MODIFY to change individual columns. MODIFY来更改各个列。For example:例如:
ALTER TABLE t MODIFY latin1_text_col TEXT CHARACTER SET utf8;
ALTER TABLE t MODIFY latin1_varchar_col VARCHAR(M) CHARACTER SET utf8;
If you specify 如果指定CONVERT TO CHARACTER SET binary, the CHAR, VARCHAR, and TEXT columns are converted to their corresponding binary string types (BINARY, VARBINARY, BLOB). CONVERT TO CHARACTER SET binary,CHAR、VARCHAR和TEXT列将转换为相应的二进制字符串类型(BINARY、VARBINARY、BLOB)。This means that the columns no longer have a character set and a subsequent 这意味着这些列不再具有字符集,后续的CONVERT TO operation does not apply to them.CONVERT TO操作将不适用于它们。
If 如果在charset_name is DEFAULT in a CONVERT TO CHARACTER SET operation, the character set named by the character_set_database system variable is used.CONVERT TO CHARACTER SET操作中charset_name是DEFAULT,则使用系统变量character_set_database命名的字符集。
The CONVERT TO operation converts column values between the original and named character sets. CONVERT TO操作在原始字符集和命名字符集之间转换列值。This is not what you want if you have a column in one character set (like 如果在一个字符集中有一列(如latin1) but the stored values actually use some other, incompatible character set (like utf8). latin1),但存储的值实际上使用了其他一些不兼容的字符集(如utf8),则这不是您想要的。In this case, you have to do the following for each such column:在这种情况下,您必须对每个此类列执行以下操作:
ALTER TABLE t1 CHANGE c1 c1 BLOB; ALTER TABLE t1 CHANGE c1 c1 TEXT CHARACTER SET utf8;
The reason this works is that there is no conversion when you convert to or from 这样做的原因是,当您转换到BLOB columns.BLOB列或从BLOB列转换时,没有转换。
To change only the default character set for a table, use this statement:要仅更改表的默认字符集,请使用以下语句:
ALTER TABLEtbl_nameDEFAULT CHARACTER SETcharset_name;
The word 单词DEFAULT is optional. DEFAULT是可选的。The default character set is the character set that is used if you do not specify the character set for columns that you add to a table later (for example, with 默认字符集是在不为以后添加到表中的列指定字符集时使用的字符集(例如,使用ALTER TABLE ... ADD column).ALTER TABLE ... ADD column)。
When the 启用系统变量foreign_key_checks system variable is enabled, which is the default setting, character set conversion is not permitted on tables that include a character string column used in a foreign key constraint. foreign_key_checks(默认设置)时,不允许在包含外键约束中使用的字符串列的表上进行字符集转换。The workaround is to disable 解决方法是在执行字符集转换之前禁用foreign_key_checks before performing the character set conversion. foreign_key_checks。You must perform the conversion on both tables involved in the foreign key constraint before re-enabling 在重新启用foreign_key_checks. foreign_key_checks之前,必须对外键约束中涉及的两个表执行转换。If you re-enable 如果在仅转换其中一个表后重新启用foreign_key_checks after converting only one of the tables, an ON DELETE CASCADE or ON UPDATE CASCADE operation could corrupt data in the referencing table due to implicit conversion that occurs during these operations (Bug #45290, Bug #74816).foreign_key_checks,则ON DELETE CASCADE或ON UPDATE CASCADE操作可能会由于这些操作期间发生的隐式转换而损坏引用表中的数据(Bug#45290,Bug#74816)。
InnoDB表An 可以使用InnoDB table created in its own file-per-table tablespace can be imported from a backup or from another MySQL server instance using DISCARD TABLEPACE and IMPORT TABLESPACE clauses. DISCARD TABLEPACE子句和IMPORT TABLESPACE子句从备份或其他MySQL服务器实例导入在每个表空间的自己的文件中创建的InnoDB表。See Section 15.6.1.3, “Importing InnoDB Tables”.请参阅第15.6.1.3节,“导入InnoDB表”。
MyISAM表的行顺序ORDER BY enables you to create the new table with the rows in a specific order. ORDER BY使您能够以特定顺序创建包含行的新表。This option is useful primarily when you know that you query the rows in a certain order most of the time. 当您知道大部分时间都是按特定顺序查询行时,此选项非常有用。By using this option after major changes to the table, you might be able to get higher performance. 通过在对表进行重大更改后使用此选项,您可能能够获得更高的性能。In some cases, it might make sorting easier for MySQL if the table is in order by the column that you want to order it by later.在某些情况下,如果表是按您以后要排序的列排序的,那么MySQL的排序可能会更容易。
The table does not remain in the specified order after inserts and deletes.插入和删除后,表不会保持指定的顺序。
ORDER BY syntax permits one or more column names to be specified for sorting, each of which optionally can be followed by ASC or DESC to indicate ascending or descending sort order, respectively. ORDER BY语法允许为排序指定一个或多个列名,每个列名后面可以可选地后跟ASC或DESC,分别表示升序或降序排序顺序。The default is ascending order. 默认值为升序。Only column names are permitted as sort criteria; arbitrary expressions are not permitted. 仅允许列名作为排序标准;不允许使用任意表达式。This clause should be given last after any other clauses.本子句应排在任何其他子句之后。
ORDER BY does not make sense for InnoDB tables because InnoDB always orders table rows according to the clustered index.ORDER BY对于InnoDB表没有意义,因为InnoDB总是根据聚集索引对表行进行排序。
When used on a partitioned table, 在分区表上使用时,ALTER TABLE ... ORDER BY orders rows within each partition only.ALTER TABLE ... ORDER BY仅在每个分区内按顺序排序行。
partition_options signifies options that can be used with partitioned tables for repartitioning, to add, drop, discard, import, merge, and split partitions, and to perform partitioning maintenance.partition_options表示可与分区表一起用于重新分区、添加、删除、放弃、导入、合并和拆分分区以及执行分区维护的选项。
It is possible for an ALTER TABLE statement to contain a PARTITION BY or REMOVE PARTITIONING clause in an addition to other alter specifications, but the PARTITION BY or REMOVE PARTITIONING clause must be specified last after any other specifications. ALTER TABLE语句可以在其他ALTER规范之外包含PARTITION BY或>REMOVE PARTITIONING子句,但PARTITION BY或>REMOVE PARTITIONING子句必须在任何其他规范之后最后指定。The ADD PARTITION, DROP PARTITION, DISCARD PARTITION, IMPORT PARTITION, COALESCE PARTITION, REORGANIZE PARTITION, EXCHANGE PARTITION, ANALYZE PARTITION, CHECK PARTITION, and REPAIR PARTITION options cannot be combined with other alter specifications in a single ALTER TABLE, since the options just listed act on individual partitions.ADD PARTITION、DROP PARTITION、DISCARD PARTITION、IMPORT PARTITION、COALESCE PARTITION、REORGANIZE PARTITION、EXCHANGE PARTITION、ANALYZE PARTITION、CHECK PARTITION和REPAIR PARTITION选项不能与单个ALTER TABLE中的其他alter规范组合,因为刚才列出的选项作用于各个分区。
For more information about partition options, see Section 13.1.20, “CREATE TABLE Statement”, and Section 13.1.9.1, “ALTER TABLE Partition Operations”. 有关分区选项的更多信息,请参阅第13.1.20节,“CREATE TABLE语句”和第13.1.9.1节,“ALTER TABLE分区操作”。For information about and examples of 有关ALTER TABLE ... EXCHANGE PARTITION statements, see Section 24.3.3, “Exchanging Partitions and Subpartitions with Tables”.ALTER TABLE ... EXCHANGE PARTITION语句的信息和示例,请参阅第24.3.3节,“用表交换分区和子分区”。