[mysql] Updating MySQL primary key

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.

This question is related to mysql primary-key

The answer is


You can use the IGNORE keyword too, example:

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

If the primary key happens to be an auto_increment value, you have to remove the auto increment, then drop the primary key then re-add the auto-increment

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

then add back the auto increment

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

then set auto increment back to previous value

ALTER TABLE `xx` AUTO_INCREMENT = 5;