[英]Delete all duplicates in mysql table
Consider the following table. 请考虑下表。 It has been imported from CSV, it does not have a primary key. 它已从CSV导入,没有主键。
+-----------+----------+----+----+----+
| 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
: 在MySQL中,最好的方法是使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.