pt-online-schema-change를 이용하여 MySQL 테이블의 키 변경

10890 단어
업무를 한동안 운영하다가 원래의 키 설정이 불합리하다는 것을 발견하고 이때 키를 변경하려고 합니다.이런 수요는 실제 생산에서 여전히 매우 많다.
다음은 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 키 삭제
# 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)

좋은 웹페이지 즐겨찾기