1

I have a table and I need the correct statement to delete duplicate records. I want to achieve this by deleting rows in the table where multiple column values equal those of other records in the same table. I can do simple delete from [table] where [col] = [val] but I have no idea how to do this. Can you provide a template that I can work from?

Thanks.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
uncle-junky
  • 723
  • 1
  • 8
  • 33

2 Answers2

1
delete from [table] 
where [col] not in 
(
  select * from 
  (
    select min([col])
    from [table]
    group by [col]
    having count(distinct [val]) <> count([val])
  ) x
)

If you select from a table you are deleting from in MySQL then you have to use a subquery to hide that. That is why I used the select * from (...) x

juergen d
  • 201,996
  • 37
  • 293
  • 362
0

Assuming that the original key's id is say 7,

DELETE FROM [table] WHERE [col1] = [val1] AND [col2] = [val2] .... AND [id] != 7;
Kevin
  • 6,539
  • 5
  • 44
  • 54
  • Thanks, though I won't be hard coding the ID in my script as there are many records in my table, so I'd like to remove all records that are like any other and keep (the most recent perhaps? I do have a timestamp of each record) one of them. I'll take a look at @juergen's answer. – uncle-junky Jun 17 '13 at 16:07