5

Possible Duplicate:
How to delete duplicate rows with SQL?

I have a table with records and I want to delete all duplicate records

DELETE FROM 'table'
WHERE 'field' IN 
(
SELECT 'field' FROM 'table' GROUP BY 'field'
HAVING (COUNT('field')>1)
)

Why isn't this working?

Community
  • 1
  • 1
vdhmartijn
  • 106
  • 2
  • 11

4 Answers4

6

Maybe you can explore with the command DISTINCT to select only unique records based in a field.

You can create a new table with the unique entries based. As an example...

CREATE TABLE nonDuplicates  
SELECT DISTINCT * FROM yourTable group by field
peixe
  • 1,165
  • 3
  • 13
  • 29
1

This gives you more than one result:-

SELECT field FROM `table`
GROUP BY field
HAVING (COUNT('field)>1

Try to chenge this by:

SELECT TOP 1 field
FROM `table`
GROUP BY field 
HAVING (COUNT(field)>1
a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843
Andrew Adamich
  • 717
  • 4
  • 8
0

First get all duplicates and store them in array.

SELECT field 
FROM `table`
GROUP BY field
HAVING COUNT('field') > 1

now do your php to save one result whichever you want and then execute

DELETE 
FROM `table`
WHERE field IN (your values) AND field != savedID
GGio
  • 7,441
  • 11
  • 41
  • 76
0

MySQL has a very obnoxious restriction that cannot use the table that is being updated/deleted/inserted in a sub-select.

But you can work around this by joining the table to be deleted (instead of using a sub-select).

Assuming you have some kind of unique identifier in your table (I assume a column id in the following statement):

DELETE d 
FROM table_with_duplicates d 
JOIN ( 
   SELECT min(id) as min_id, field
   FROM table_with_duplicates 
   GROUP BY field
) keep ON keep.field = d.field
      AND keep.min_id <> d.id; 

This will keep one row for each of the duplicates (the one with the lowes value in the id column).

If you want to delete all duplicate rows (not keeping at least one), simply remove the AND keep.min_id <> d.id condition.

Edit

If you don't have a unique column, but want to remove all duplicates (not keeping at least one row), then you can use:

DELETE d 
FROM table_with_duplicates d 
JOIN ( 
   SELECT field
   FROM table_with_duplicates 
   GROUP BY field
   HAVING count(*) > 1
) del ON del.field = d.field;
a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843