在引入在线 DDL之前,将多个 DDL 操作合并到单个ALTER TABLE语句中是一种常见做法。由于每个ALTER TABLE语句都涉及复制和重建表,同时对同一个表进行多个更改更为高效,因为这些更改都可以通过一次表重建操作完成。缺点是涉及 DDL 操作的 SQL 代码更难维护,也不容易在不同的脚本中重用。如果每次特定的更改都不同,您可能需要为每个略有不同的情况构造一个新的复杂ALTER
TABLE语句。Before the introduction of online
DDL, it was common practice to combine many DDL operations
into a single ALTER TABLE
statement. Because each ALTER TABLE
statement involved copying and rebuilding the table, it was more
efficient to make several changes to the same table at once, since
those changes could all be done with a single rebuild operation
for the table. The downside was that SQL code involving DDL
operations was harder to maintain and to reuse in different
scripts. If the specific changes were different each time, you
might have to construct a new complex ALTER
TABLE for each slightly different scenario.
对于可以在线执行的 DDL 操作,您可以将它们拆分为单独的ALTER TABLE语句,以便于脚本编写和维护,同时不影响效率。例如,您可以将一个复杂的语句拆分为:For DDL operations that can be done online, you can separate them
into individual ALTER TABLE
statements for easier scripting and maintenance, without
sacrificing efficiency. For example, you might take a complicated
statement such as:
ALTER TABLE t1 ADD INDEX i1(c1), ADD UNIQUE INDEX i2(c2), CHANGE c4_old_name c4_new_name INTEGER UNSIGNED;
并将其分解为可以独立测试和执行的更简单的部分,例如:and break it down into simpler parts that can be tested and performed independently, such as:
ALTER TABLE t1 ADD INDEX i1(c1); ALTER TABLE t1 ADD UNIQUE INDEX i2(c2); ALTER TABLE t1 CHANGE c4_old_name c4_new_name INTEGER UNSIGNED NOT NULL;
您仍然可以使用多部分的ALTER
TABLE语句来处理:You might still use multi-part ALTER
TABLE statements for:
必须按特定顺序执行的操作,例如先创建索引,然后创建使用该索引的外键约束。Operations that must be performed in a specific sequence, such as creating an index followed by a foreign key constraint that uses that index.
所有操作都使用相同的特定
LOCK子句,希望它们作为一个整体成功或失败的操作。Operations all using the same specificLOCKclause, that you want to either succeed or fail as a group.无法在线执行的操作,即仍然使用表复制方法的操作。Operations that cannot be performed online, that is, that still use the table-copy method.
对于您指定了
ALGORITHM=COPY或old_alter_table=1的操作,如果在特殊场景下需要精确的向后兼容性,可以强制使用表复制行为。Operations for which you specifyALGORITHM=COPYorold_alter_table=1, to force the table-copying behavior if needed for precise backward-compatibility in specialized scenarios.