mysql根据主键更新,更新MySQL主键

I have a table user_interactions with 4 columns:

user_1

user_2

type

timestamp

The primary key is (user_1,user_2,type)

and I want to change to (user_2,user_1,type)

So what I did was :

drop primary key ...

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

and voila...

The problem is that database is live on a server.

So before I could update the primary key, many duplicates already crept in, and they are continuously creeping in.

What to do?

What I want to do now is to remove duplicates and keep the ones with the latest timestamp (which is a column in the table).

And then somehow update the primary key again.

解决方案

Next time, use a single "alter table" statement to update the primary key.

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

To fix things:

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;

The lock should stop further updates coming in while your are doing this. How long this takes obviously depends on the size of your table.

The main problem is if you have some duplicates with the same timestamp.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值