如何删除SQL中的重复行?

时间:2014-07-12 14:40:08

标签: sql phpmyadmin duplicate-removal

我的表名是emails

我的表格结构如下:

enter image description here

我想删除所有重复的电子邮件。我试过这个问题:

DELETE FROM emails WHERE email NOT IN (SELECT MIN(email)
    FROM emails GROUP BY email) 

但没有结果。有人可以帮我这个吗?

3 个答案:

答案 0 :(得分:2)

您要查找的查询将使用id,而不是email

DELETE FROM emails
    WHERE id NOT IN (SELECT MIN(id) FROM emails GROUP BY email) ;

编辑:

您正在使用MySQL。您可以使用子查询黑客来解决这个问题:

DELETE FROM emails
    WHERE id NOT IN (select minid from (SELECT MIN(id) as minid FROM emails GROUP BY email) e) ;

或者,您可以使用join

delete e
    from emails e left outer join
         (select min(id) as minid
          from emails
          group by email
         ) em
         on e.id = e.minid
    where em.id is null;

答案 1 :(得分:0)

试试这个

- 创建临时表

create table IDsToRemove (ID Int)
INSERT INTO IDStoRemove
     SELECT MIN(id) _
            FROM emails GROUP BY email 


      DELETE FROM emails WHERE id NOT IN (SELECT id from IDStoRemove) 

我不知道确切的mySQL语法,但应该给你一个想法

答案 2 :(得分:0)

也许你(或某人)想要删除独特的记录,我会在这里留下这个被盗的答案[0]。

DELETE Emails 
FROM Emails
  LEFT OUTER JOIN (
    SELECT MIN(id) as id, email, pwd
    FROM Emails
    GROUP BY email, pwd
  ) as KeepRows ON
  Emails.id = KeepRows.id
WHERE
  KeepRows.id IS NULL

0。How can I remove duplicate rows?