2

How I can create an SQL command to delete all rows from table where I have two or more specific columns with the same value and still I don't lose that row, only the duplicates?

For example:

Id      value1     value2
1          71            5
2          8             8
3          8             8
4          8             8
5          23           26

Id2, Id3 and Id4 have same value1 and value2.

I need to delete all duplicate rows like (Id3 and Id4) or (Id2 and Id4) or (Id2 and Id3)

4
  • 3
    So many duplicates in the "related" column Commented Feb 29, 2012 at 11:34
  • Duplicate? : stackoverflow.com/questions/5921167/… Commented Feb 29, 2012 at 11:37
  • use distinct(value1),distinct(value2) in your table Commented Feb 29, 2012 at 11:40
  • I thought distinct worked on a column level. Not a field level. As the Ids differ, Distinct wont work? Commented Feb 29, 2012 at 11:59

3 Answers 3

2
delete t
from table1 t
inner join table1 t2
on t.id>t2.id and t.value1=t2.value1 and t.value2=t2.value2
Sign up to request clarification or add additional context in comments.

Comments

0

Since MySQL allows ungrouped fields in queries:

CREATE TEMPORARY TABLE ids AS
  (SELECT id
    FROM your_table
    GROUP BY value1, value2);

DELETE FROM your_table
  WHERE id NOT IN (SELECT id FROM ids);

Comments

0

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

select distinct * into NewTable from MyTable

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.