考虑下表。它已从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 |
+-----------+----------+----+----+----+
我想删除表中不止一次出现(firstname,lastname)的所有行。所以输出将是:
+-----------+----------+----+----+----+
| firstname | lastname | c1 | c2 | c3 |
+-----------+----------+----+----+----+
| john | doe | p | q | r |
+-----------+----------+----+----+----+
答案 0 :(得分:4)
在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;
答案 1 :(得分:0)
您可以选择以下内容而不是删除。
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
但是如果你想删除,那就按照以下方式执行
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
答案 2 :(得分:0)
delete from table_name n
where (select count(*) from table_name z
where n.firstname = z.firstname and n.lastname = z.lastname) > 1