Monday, 18 June 2012

Delete duplicate entries/rows/values in mysql table in one query

How can you delete or remove duplicate entries from a mysql table, without having to use PHP logic etc ?

The query would be

CREATE TABLE MyNewTable AS SELECT * FROM MyOldTable WHERE 1 GROUP BY [COLUMN TO remove duplicates BY];
 
This would create a new table with name MyNewTable which will have unique values for the column specified in the query. Now we do not require the MyOldTable, hence can be removed, followed by a query that will rename the new table to the old table..

DROP TABLE MyOldTable;
RENAME TABLE MyNewTable TO MyOldTable;

No comments:

Post a Comment