Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Duplicate error with ALTER IGNORE TABLE

I have a table in my MySQL with duplicates. I try to delete the duplicates and keep one entry. I don't have a primary key

I can finde the duplicates by:

select user_id, server_id, count(*) as NumDuplicates
from user_server
group by user_id, server_id
having NumDuplicates > 1

But can't delete them with:

ALTER IGNORE TABLE `user_server`  
ADD UNIQUE INDEX (`user_id`, `server_id`);

Even SET foreign_key_checks = 0; is not working. Error Code: 1062. Duplicate entry '142-20' for key 'user_id_3'

MySQL version: 5.5.18 Engine: InnoDB

Is there an other way?

like image 478
blubbering Avatar asked Dec 15 '14 20:12

blubbering


1 Answers

It's because you use INNO DB,

A simple trick :

set session old_alter_table=1;
ALTER IGNORE TABLE `user_server`  
ADD UNIQUE INDEX (`user_id`, `server_id`);
set session old_alter_table=0;

This do the job

like image 105
Reign.85 Avatar answered Oct 11 '22 13:10

Reign.85