时间:2021-07-01 10:21:17 帮助过:13人阅读
下面,看看pt-online-schema-change解决这类问题的处理方式。
首先,创建一张测试表
create table t2(c1 int primary key, c2 int);
构造测试数据
delimiter //
create procedure p1()
begin
declare v1 int default 1;
set autocommit=0;
while v1 <=100000 do
insert into test.t2(c1,c2) values(v1,v1+100);
set v1=v1+1;
if v1%1000 =0 then
commit;
end if;
end while;
end //
delimiter ;
call p1;下面,开始使用pt-online-schema-change对t2表进行主键变更
1. 对c1列加上unique key
# pt-online-schema-change --execute --alter "modify c1 int unique key" --print D=test,t=t2
此时,t2表的表结构如下:
mysql> show create table t2\G
*************************** 1. row ***************************
Table: t2
Create Table: CREATE TABLE `t2` (
`c1` int(11) NOT NULL DEFAULT '0',
`c2` int(11) DEFAULT NULL,
PRIMARY KEY (`c1`),
UNIQUE KEY `c1` (`c1`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
row in set (0.03 sec)2. 删除c1列上的主键
# pt-online-schema-change --execute --alter "drop primary key" --no-check-alter --print D=test,t=t2
注意:删除主键需加上 --no-check-alter选项
此时,t2的表结构如下:
mysql> show create table t2\G
*************************** 1. row ***************************
Table: t2
Create Table: CREATE TABLE `t2` (
`c1` int(11) NOT NULL DEFAULT '0',
`c2` int(11) DEFAULT NULL,
UNIQUE KEY `c1` (`c1`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
row in set (0.05 sec)3. 添加c2列上的主键
# pt-online-schema-change --execute --alter "modify c2 int primary key" --print D=test,t=t2
此时,t2的表结构如下:
mysql> show create table t2\G
*************************** 1. row ***************************
Table: t2
Create Table: CREATE TABLE `t2` (
`c1` int(11) NOT NULL DEFAULT '0',
`c2` int(11) NOT NULL,
PRIMARY KEY (`c2`),
UNIQUE KEY `c1` (`c1`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
row in set (0.02 sec)4. 删除c1列上的unique key
# pt-online-schema-change --execute --alter "drop key c1" --print D=test,t=t2
此时,t2的主键变更完成
mysql> show create table t2\G
*************************** 1. row ***************************
Table: t2
Create Table: CREATE TABLE `t2` (
`c1` int(11) NOT NULL DEFAULT '0',
`c2` int(11) NOT NULL,
PRIMARY KEY (`c2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
row in set (0.02 sec)