Thomas Bergheim dot com | Random ramblings on technology

Making fields unique when there are duplicate rows in mysql

So I had this table working as a many-to-many relationship for some things, with 2 fields, both foreign keys to other tables. Since there for some reason wasn’t anything enforcing uniqueness in the entries, there were several duplicate rows. If I tried to ALTER TABLE to add a primary key to the 2 fields (no PK was defined before), I’d ofcourse get a duplicate key error. I thought about it a bit – how can I clamp the duplicate fields on this thing without scripting?

After going back and forth with a few alter and join commands, it hit me; create a new table with the same properties, in addition to the primary keys, and populate it with the contents of the original table, ignoring duplicates. Easy!

INSERT IGNORE INTO new SELECT * FROM original

Back to Top

Write a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>