更新MySQL主键

时间:2010-02-26 12:42:19

标签: mysql primary-key

我有一个包含4列的表user_interactions

 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(表格中的一列)。

然后以某种方式再次更新主键。

3 个答案:

答案 0 :(得分:190)

下次使用单个“alter table”语句更新主键。

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;

当你这样做时,锁应该停止进一步的更新。这需要多长时间取决于你桌子的大小。

主要问题是,如果您有一些具有相同时间戳的重复项。

答案 1 :(得分:8)

如果主键恰好是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;

答案 2 :(得分:2)

您也可以使用IGNORE关键字,例如:

 update IGNORE table set primary_field = 'value'...............
相关问题