0

My table name is emails.

My table structures looks like:

enter image description here

I want to remove all of the duplicated emails. I tried this query:

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

But with no result. Can someone help me with this?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Attila Naghi
  • 2,535
  • 6
  • 37
  • 59

3 Answers3

2

The query that you are looking for would use id, not email:

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

EDIT:

You are using MySQL. You can get around this with the subquery hack:

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

Or, you can use a 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;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Try this instead

--CREATE a Temporary table

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) 

I don't know the exact mySQL syntax, but should give you the idea

Sparky
  • 14,967
  • 2
  • 31
  • 45
0

Maybe you (or someone) wants to delete records that are unique, I'll just leave this stolen answer here[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?

Community
  • 1
  • 1
keppy
  • 46
  • 2