数据库
首页 > 数据库> > mysql – 删除表的多个KEYS

mysql – 删除表的多个KEYS

作者:互联网

在表中删除多个KEYS是首选选项还是逐个删除?

“DROP KEY A,DROP KEY B,DROP KEY C”

表中有超过9亿条记录.

它在内部如何运作?

解决方法:

在一个SQL命令中删除多个索引更好.为什么?

场景#1

ALTER TABLE mytable DROP INDEX ndx1;
ALTER TABLE mytable DROP INDEX ndx2;
ALTER TABLE mytable DROP INDEX ndx3;

这就是会发生的事情

>创建一个空的临时表
>从空临时表中删除索引
>将数据复制到临时表中
>用原始表交换临时表
>丢弃原始表

在#SCENARIO#1中,这将发生三次.

场景#2

ALTER TABLE mytable
    DROP INDEX ndx1,
    DROP INDEX ndx2,
    DROP INDEX ndx3
;

您是否相信MySQL曾经在2006年的MySQL 4.1下进行过3次转换?换句话说,SCENARIO#2将像SCENARIO#1一样处理.我实际上在MySQL AB一般论坛中写了一篇文章,要求对其进行更改(Why does mysql drop index very very slow in a large table?).

有人在DBA StackExchange中询问MySQL是否仍然这样做.我在这里写了一篇文章,说这不再是这种情况(Does MySQL still handle indexes in this way?),那个问题引用了my original MySQL AB post.

MySQL今天做的是:

>创建临时表
>针对空临时表运行3个ALTER TABLE命令
>将数据复制到临时表ONCE
>用原始表交换临时表
>丢弃原始表

因此,您可以相信MySQL今天会做正确的事情.

你应该选择SCENARIO#2.

试试看 !!!

更新2015-01-02 13:06美国东部时间

你问过

What will happen to new operations to the table? Where will new records gets stored at the time of copying? Would it take table lock or metadata lock ?

该表将在整个时间内被锁定.当然,SCENARIO#1的锁定时间是SCENARIO#2的三倍.如果您无法停止此操作,则只有一个选项:pt-online-schema-change.更改期间将正确处理所有INSERT,UPDATE和DELETE.

更新2015-01-03 08:33美国东部时间

@eroomydna just posted a comment.

@rolando, had you considered the effect of dev.mysql.com/doc/refman/5.5/en/innodb-create-index.html and is default on 5.6. Table should not be rebuilt with the above grouped ddl. No need to use pt-osc for this operation.

@eroomydna指出这一点是正确的.他提供的URL可以深入了解这一点.

对于你的特定问题,@ aeromydna说不需要pt-online-schema-change,他在这个例子中是正确的,因为你丢弃了三个索引.注意Implementation Details of Fast Index Creation, Paragraph 2

Dropping a secondary index is simple. Only the internal InnoDB system tables and the MySQL data dictionary tables are updated to reflect the fact that the index no longer exists. InnoDB returns the storage used for the index to the tablespace that contained it, so that new indexes or additional table rows can use the space.

你有一个9亿的表,可能还有很多索引页面.正在以逻辑方式删除索引,并且必须使所有这些页面无效以使该空间可重用.这还将创建许多共享锁,允许读取和阻止写入.所以,这个操作应该相对较快.我需要多长时间才能告诉你.既然你说你不能承受停机时间,那么对于有大量共享锁和被阻止写入的实时表,它可能是几秒,几分钟甚至几小时.

如果您在DEV或测试服务器上有该表的副本,请运行DROP KEY A,DROP KEY B,DROP KEY C,以便您可以看到它的运行速度.然后,您可以考虑停机时间是否值得.尽管如此,如果你想让桌子上线并且真的无法完成停机,你仍然可以使用pt-online-schema-change.

至于我的答案,它只适用于

>删除索引并创建具有相同名称的索引
>删除/添加PRIMARY KEY

标签:mysql,innodb,alter-table,index
来源: https://codeday.me/bug/20190805/1593769.html