it-source

MySQL 기본 키 업데이트 중

criticalcode 2022. 10. 21. 22:46
반응형

MySQL 기본 키 업데이트 중

테이블이 있습니다user_interactions4열 포함:

 user_1
 user_2
 type
 timestamp

주요 키는 다음과 같습니다.(user_1,user_2,type)
그리고 나는 바꾸고 싶다.(user_2,user_1,type)

그래서 내가 한 일은:

drop primary key ...  
add primary key (user_2,user_1,type)...

그리고 부라...

문제는 데이터베이스가 서버에서 활성화되어 있다는 것입니다.

그래서 프라이머리 키를 업데이트하기 전에 이미 많은 복제품이 슬금슬금 들어오고 있습니다.

무엇을 해야 하나?

내가 지금 하고 싶은 것은 중복된 것을 제거하고 최신의 것을 유지하는 것이다.timestamp(테이블의 컬럼).

그런 다음 기본 키를 다시 업데이트합니다.

다음 번에는 단일 "변경 테이블" 문을 사용하여 기본 키를 업데이트합니다.

alter table xx drop primary key, add primary key(k1, k2, k3);

문제를 해결하려면:

create table fixit (user_2, user_1, type, timestamp, n, primary key( user_2, user_1, type) );
lock table fixit write, user_interactions u write, user_interactions write;

insert into fixit 
select user_2, user_1, type, max(timestamp), count(*) n from user_interactions u 
group by user_2, user_1, type
having n > 1;

delete u from user_interactions u, fixit 
where fixit.user_2 = u.user_2 
  and fixit.user_1 = u.user_1 
  and fixit.type = u.type 
  and fixit.timestamp != u.timestamp;

alter table user_interactions add primary key (user_2, user_1, type );

unlock tables;

이 작업을 수행하는 동안 잠금이 추가 업데이트 수신을 중지합니다.시간이 걸리는 것은 테이블의 크기에 따라 다릅니다.

주된 문제는 타임스탬프가 같은 중복이 있는 경우입니다.

프라이머리 키가 auto_increment 값일 경우 auto increment를 삭제하고 프라이머리 키를 드롭한 후 auto-increment를 다시 추가해야 합니다.

ALTER TABLE `xx`
MODIFY `auto_increment_field` INT, 
DROP PRIMARY KEY, 
ADD PRIMARY KEY (new_primary_key);

그런 다음 자동 증가분을 다시 추가합니다.

ALTER TABLE `xx` ADD INDEX `auto_increment_field` (auto_increment_field),
MODIFY `auto_increment_field` int auto_increment;

그런 다음 자동 증가를 이전 값으로 다시 설정합니다.

ALTER TABLE `xx` AUTO_INCREMENT = 5;

를 사용할 수 있습니다.IGNORE키워드도 있습니다.예:

 update IGNORE table set primary_field = 'value'...............

언급URL : https://stackoverflow.com/questions/2341576/updating-mysql-primary-key

반응형