重命名锁定的表

tcu*_*rdt 2 mysql mariadb

将表迁移到新模式时,我希望确保使用复制和重命名过程将原子切换到新表.因此,我试图重命名一个锁定的表,如下所示:

CREATE TABLE foo_new (...)

-- copy data to new table, might take very long
INSERT INTO foo_new (id,created_at,modified_at)
  SELECT * FROM foo WHERE id <= 3;

LOCK TABLES foo WRITE, foo_new WRITE;

-- quickly copy the tiny rest over
INSERT INTO foo_new (id,created_at,modified_at)
  SELECT * FROM foo WHERE id > 3;

-- now switch to the new table
RENAME TABLE foo TO foo_old, foo_new TO foo;

UNLOCK TABLES;
Run Code Online (Sandbox Code Playgroud)

不幸的是,导致了ERROR 1192 (HY000): Can't execute the given command because you have active locked tables or an active transaction.

应如何做到这一点?

这是mariadb:10.1.

tcu*_*rdt 8

虽然一般来说Rick使用Percona工具是正确的(见12),但问题的答案实际上是使用ALTER TABLE.我认为RENAME这只是一个别名 - 但似乎并非如此.

测试似乎表明这个工作正常:

CREATE TABLE foo_new (...)

-- copy data to new table, might take very long
INSERT INTO foo_new (id,created_at,modified_at)
  SELECT * FROM foo WHERE id <= 3;

LOCK TABLES foo WRITE, foo_new WRITE;

-- quickly copy the tiny rest over
INSERT INTO foo_new (id,created_at,modified_at)
  SELECT * FROM foo WHERE id > 3;

-- now switch to the new table
ALTER TABLE foo RENAME TO foo_old;
ALTER TABLE foo_new RENAME TO foo;

UNLOCK TABLES;
Run Code Online (Sandbox Code Playgroud)