Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete duplicate records in mysql database?

What's the best way to delete duplicate records in a mysql database using rails or mysql queries?

like image 583
nan Avatar asked Mar 18 '09 20:03

nan


People also ask

How do you delete duplicate records in database?

To delete the duplicate rows from the table in SQL Server, you follow these steps: Find duplicate rows using GROUP BY clause or ROW_NUMBER() function. Use DELETE statement to remove the duplicate rows.


2 Answers

What you can do is copy the distinct records into a new table by:

 select distinct * into NewTable from MyTable
like image 107
TStamper Avatar answered Oct 07 '22 01:10

TStamper


Here's another idea in no particular language:

rs = `select a, b, count(*) as c from entries group by 1, 2 having c > 1`
rs.each do |a, b, c|
  `delete from entries where a=#{a} and b=#{b} limit #{c - 1}`
end

Edit:

Kudos to Olaf for that "having" hint :)

like image 29
krukid Avatar answered Oct 07 '22 03:10

krukid