Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL Delete FIRST duplicates from table

Tags:

sql

mysql

I have 511 duplicates in my table, I need to delete these, but not the originals. Therefore I want to delete every second occurrence of every duplicate.

How can I do this?

TABLE:

code  /   status  /   time
E3F4FF928A  /  0 /
07D95444BB  /  0 /  
07D95444BB /   0 / 
40006C128F  / 0  / 1315293012
2B45790E52   /  0  /
40006C128F  / 0  / 1315293012
like image 590
Jake Avatar asked Sep 07 '11 20:09

Jake


People also ask

How do you remove the duplicates record of a table?

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.

How do I find duplicate records in the same table in MySQL?

Find Duplicate Row values in One Column SELECT col, COUNT(col) FROM table_name GROUP BY col HAVING COUNT(col) > 1; In the above query, we do a GROUP BY for the column for which we want to check duplicates. We also use a COUNT() and HAVING clause to get the row counts for each group.


2 Answers

add a unique index to the table on the column that should be unique, and ignore errors

alter ignore table X add unique index (column_a) 

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

like image 78
Zak Avatar answered Oct 05 '22 04:10

Zak


Just run into this problem today (no unique key in the table).

I solved it like this

DELETE FROM table where code=x and status=y and time=z LIMIT 1;

This will delete the first 1 row for the given criteria (if you have n duplicates, put n-1 to keep only one).

like image 43
sikrip Avatar answered Oct 05 '22 02:10

sikrip