Mysql add mult-column index with repeated rows
-
28-09-2019 - |
Question
Having the next table:
id -> incremental
field_1 -> foreignkey
field_2 -> foreignkey
I want to add the next index
ALTER TABLE my_table ADD unique index(field_1, field_2);
How ever I have (due a bad application validation) I have a lot of repeated rows (by repeated I mean same field_1 and same field_2, having just id as difference)
The table has about 60,000 rows so... removing field by field would be very hard.
How can I apply that index and remove every duplicated row?
Solution
create table mytable2 like mytable;
insert into mytable2
select max(id), field_1, field_2
from mytable
group by field_1, field_2;
rename table mytable to mytable_old, mytable2 to mytable;
ALTER TABLE my_table ADD unique index(field_1, field_2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow