Possible Duplicate:
How to delete Duplicates in MySQL table
I imported data that I had in plain text files into a mysql database. Now I found I had duplicated entries, which I want to delete. The duplicates are identified by a key which is not the primary key. Please remind that I have to keep one of the duplicated items.
the table, T1, with three duplicates, for example:
ID(unique, primary key) REAL_ID(char(11))
1 '01234567890' 2 '01234567891' 3 '01234567891' 4 '01234567891' ...
Now, I use
SELECT ID AS x, COUNT(*) AS y FROM T1 GROUP BY x HAVING y>1;
to identify the duplicates. The result i
+------+-------------+ | ID | REAL_ID | +------+-------------+ | 1 | 01234567891 | | 2 | 01234567891 | | 3 | 01234567891 | +------+-------------+
I can even construct the list of the Ids I have to delete:
SELECT ID
FROM T1
RIGHT JOIN ( (SELECT ID AS x, COUNT(*) AS y
FROM T1
GROUP BY x
HAVING y>1) AS T2 ) ON (T2.x=T1.REAL_ID) LIMIT 1,100;
The result is
+------+-------------+ | ID | REAL_ID | +------+-------------+ | 2 | 01234567890 | | 3 | 01234567890 | +------+-------------+
Now, I need help on how to delete these entries.
Since is not possible to use DELETE in combination with subqueries, I was trying to flag all the duplicated entries in the column REAL_ID, and then use
DELETE FROM T1 WHERE REAL_ID='flag';
but I can't figure out how to flag these entries.