PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

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

高洛峰
高洛峰 原创
2016-10-29 10:53:23 1720浏览

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

下面,看看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表的表结构如下:

<a style='color:#f60; text-decoration:underline;' href="https://m.php.cn/zt/15713.html" target="_blank">mysql</a>> show create table t2\G
*************************** 1. row ***************************
       Table: t2
Create Table: CREATE TABLE `t2` (
  `c1` int(11) NOT NULL DEFAULT &#39;0&#39;,
  `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 &#39;0&#39;,
  `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 &#39;0&#39;,
  `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 &#39;0&#39;,
  `c2` int(11) NOT NULL,
  PRIMARY KEY (`c2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
row in set (0.02 sec)
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。