Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Atualizando a chave primária do MySQL


Da próxima vez, use uma única instrução "alter table" para atualizar a chave primária.
alter table xx drop primary key, add primary key(k1, k2, k3);

Para consertar as coisas:
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;

O bloqueio deve impedir que outras atualizações cheguem enquanto você está fazendo isso. Quanto tempo isso leva obviamente depende do tamanho da sua mesa.

O principal problema é se você tiver algumas duplicatas com o mesmo timestamp.