Reputation: 3
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 |
+-----------+----------+----+----+----+
Upvotes: 0
Views: 108
Reputation: 3880
delete from table_name n
where (select count(*) from table_name z
where n.firstname = z.firstname and n.lastname = z.lastname) > 1
Upvotes: 0
Reputation: 1269463
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;
Upvotes: 4
Reputation: 1912
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
Upvotes: 0