DELETE t2 FROM table1 t2 INNER JOIN table1 t1 ON (t1.somefield = t2.somefield AND t1.otherfield = t2.otherfield /*add more fields if need be */ AND t2.id > t1.id) LEFT JOIN table1 t3 ON (t1.somefield = t3.somefield AND t1.otherfield = t3.otherfield /*add more fields if need be */ AND t3.id > t2.id) WHERE (t3.id IS NULL) ORDER BY t2.id ASC
This should remove only the 2nd duplicate and leave only the 3rd and more duplicates.
If you want something less esoteric and you have a timestamp column, maybe you want to do
DELETE t2 FROM table1 t2 INNER JOIN table1 t1 ON (t1.somefield = t2.somefield AND t1.otherfield = t2.otherfield /*add more fields if need be */ AND t2.`timestamp` > t1.`timestamp`) WHERE (1=1) /*In some mode(s) MySQL requires a where clause with delete*/ ORDER BY t2.id ASC
Johan
source share