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 |
+-----------+----------+----+----+----+
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;
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
delete from table_name n
where (select count(*) from table_name z
where n.firstname = z.firstname and n.lastname = z.lastname) > 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.