mysqlsql-deletedelete-rowunique-constraint

How to delete all rows in a group except the newest one?


Say, I have a table similar to this:

CREATE TABLE `mytable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `application_id` int(11) NOT NULL,
  `company_name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB

I want to make application_id unique, but there're some duplicates in the table already. How can I group by application_id and remove all records per group, leaving just the one with the highest id?


Solution

  • You can use a multi-table DELETE with a self-join:

    DELETE t1 FROM mytable t1 INNER JOIN mytable t2
    WHERE t1.application_id = t2.application_id AND t1.id < t2.id
    

    How it works: