Lets say I have this users
table:
id email
1 test@gmail.com
2 xxp@gmail.com
3 test@gmail.com
4 zzz@gmail.com
And I want to delete rows that have duplicated emails
.
First I thought of retrieving duplicated emails:
select id
group by email
having count(*)>1
Which results in:
updated result
1
Then I added the delete
clause:
delete from users
where id in(
select id
group by email
having count(*)>1 )
The result is No Errors, but 0 rows affected... which means nothing happened.
I want to know what I'm doing wrong and some other ways of doing this.
Specifications: MySQL 5.5.5-10.1.16-MariaDB Using Sequel Pro on Mac
Thanks
You can do a sub-query to get the id or ids having duplicate then remove it from your table. See demo here: http://sqlfiddle.com/#!9/f14d05/1
DELETE from users
where id in (
SELECT id
from (
SELECT a.id, count(*) as rn
FROM users a
JOIN users b ON a.email = b.email AND a.id <= b.id
GROUP BY a.id, a.email
) t
where rn>1
);