我有一个包含列的数据库表:email,name,id
存在具有相同电子邮件和名称的重复记录(ID可能会也可能不同)
我想删除所有副本,而不是保留其中任何副本。
实施例
email | name | id
-------------------------------------------------
a@b.com | a | 2 --- remove
a@b.com | a | 4 --- remove
b@c.com | b | 3
c@d.com | c | 5
我可以在phpmyadmin中使用什么SQL查询来执行此操作?
答案 0 :(得分:2)
您可以使用EXISTS
:
DELETE FROM TableName t1
WHERE EXISTS
(
SELECT 1 FROM TableName t2
WHERE t1.id <> t2.id
AND COALESCE(t1.email,'') = COALESCE(t2.email,'')
AND COALESCE(t1.name,'') = COALESCE(t2.name,'')
)
如果电子邮件或名称为空,我已使用COALESCE
删除重复项。
答案 1 :(得分:0)
在MySQL中,您应该使用join
:
delete t
from example t join
(select email, name
from example
group by email, name
having count(*) > 1
) todelete
on t.email = todelete.email and t.name = todelete.name;
不幸的是,MySQL不支持在update
或delete
语句中修改的表上的简单子查询。
编辑:
删除大量记录可能是性能瓶颈。要解决此问题,请创建一个包含所需记录的临时表,截断原始表,然后重新插入它们。
所以,试试这个:
create temporary table tempt as
select t.*
from example t join
(select email, name
from example
group by email, name
having count(*) = 1
) tokeep
on t.email = tokeep.email and t.name = tokeep.name;
truncate table example;
insert into example
select * from tempt;
首先尝试select
查询以确保其具有合理的性能并按照您的意愿行事。
答案 2 :(得分:-1)
删除n1 FROM tablename n1,tablename n2 WHERE n1.email = n2.email