0

Consider the following table. It has been imported from CSV, it does not have a primary key.

+-----------+----------+----+----+----+ | firstname | lastname | c1 | c2 | c3 | +-----------+----------+----+----+----+ | johnny | bravo | a | b | c | | bruce | willis | x | y | x | | john | doe | p | q | r | | johnny | bravo | p | q | r | | johnny | bravo | p | q | r | | bruce | willis | x | y | z | +-----------+----------+----+----+----+ 

I want to delete all rows where (firstname, lastname) appear more than once in the table. So the output would be:

+-----------+----------+----+----+----+ | firstname | lastname | c1 | c2 | c3 | +-----------+----------+----+----+----+ | john | doe | p | q | r | +-----------+----------+----+----+----+ 
2
  • Possible duplicate of How can I remove duplicate rows? Commented Oct 24, 2016 at 11:48
  • What's your PRIMARY KEY? Commented Oct 24, 2016 at 11:55

3 Answers 3

4

In MySQL, the best way is to use join:

delete t from t join ( select t2.firstname, t2.lastname from t t2 group by t2.firstname, t2.lastname having count(*) > 1 ) t2 on t.firstname = t2.firstname and t.lastname = t2.lastname; 
Sign up to request clarification or add additional context in comments.

Comments

0

You can select as following instead of delete.

SELECT * FROM TABLE A INNER JOIN ( SELECT FirstName, LastName, COUNT(firstname) AS num FROM TABLE GROUP BY FirstName, LastName ) B ON A.FirstName = B.FirstName AND A.LastName = B.LastName WHERE B.num = 1 

But if you wanna delete then do as following

DELETE A FROM TABLE A INNER JOIN ( SELECT FirstName, LastName, COUNT(firstname) AS num FROM TABLE GROUP BY FirstName, LastName ) B ON A.FirstName = B.FirstName AND A.LastName = B.LastName WHERE B.num > 1 

Comments

0
delete from table_name n where (select count(*) from table_name z where n.firstname = z.firstname and n.lastname = z.lastname) > 1 

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.