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
?
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:
INNER
(CROSS
) join; that is, each and every row in the table is joined to each and every row in the same table.WHERE
condition filters the rows with the same application_id
- this is effectively the "grouping" part - and the ones with lower id
s. Those are removed from the target table, keeping only rows with the highest id
per application_id
.