[英]delete ids from subquery results
Lets say I have this users
table: 可以说我有这个
users
表:
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
. 我想删除重复
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
子句:
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. 结果是没有错误,但是0行受影响了……这意味着什么也没发生。
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 规格:在Mac上使用Sequel Pro的MySQL 5.5.5-10.1.16-MariaDB
Thanks 谢谢
You can do a sub-query to get the id or ids having duplicate then remove it from your table. 您可以执行子查询以获取具有重复项的一个或多个ID,然后将其从表中删除。 See demo here: http://sqlfiddle.com/#!9/f14d05/1
在此处查看演示: 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
);
Tested on MSSQL. 在MSSQL上测试。
select min(id) id, email
into #users
from [users]
group by email
delete from [users] where id not in (select id from #users)
drop table #users
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.