業務運行一段時間,發現原來的主鍵設置並不合理,這個時候,想變更主鍵。這種需求在實際生產中還是蠻多的。
下面,看看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
1 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
1 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
1 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
1 row in set (0.02 sec)