您好,欢迎访问一九零五行业门户网

pt-online-schema-change进行MySQL表的主键变更

业务运行一段时间,发现原来的主键设置并不合理,这个时候,想变更主键。这种需求在实际生产中还是蛮多的。
下面,看看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 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)
其它类似信息

推荐信息