• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

mysql 搞代码 4年前 (2022-01-09) 40次浏览 已收录 0个评论

业务运行一段时间,发现原来的主键设置并不合理,这个时候,想变更主键。这种需求在实际生产中还是蛮多的。

下面,看看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: t2Create Table: CREATE TABLE `t2` (  `c1` int(11) NOT NULL DEFAULT '0',  `c2` int(11) DEFAULT NULL,  PRIMARY KEY (`c1`),  UNIQUE KEY<em>本文来源gao.dai.ma.com搞@代*码(网$</em> `c1` (`c1`)) ENGINE=InnoDB DEFAULT CHARSET=utf8row 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: t2Create Table: CREATE TABLE `t2` (  `c1` int(11) NOT NULL DEFAULT '0',  `c2` int(11) DEFAULT NULL,  UNIQUE KEY `c1` (`c1`)) ENGINE=InnoDB DEFAULT CHARSET=utf8row 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: t2Create 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=utf8row 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: t2Create Table: CREATE TABLE `t2` (  `c1` int(11) NOT NULL DEFAULT '0',  `c2` int(11) NOT NULL,  PRIMARY KEY (`c2`)) ENGINE=InnoDB DEFAULT CHARSET=utf8row in set (0.02 sec)

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:pt-online-schema-change进行MySQL表的主键变更

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址