从子查询结果中删除 id

delete ids from subquery results

假设我有这个 users table:

id email
1  test@gmail.com
2  xxp@gmail.com
3  test@gmail.com
4  zzz@gmail.com

我想删除重复的行 emails

首先我想到了检索重复的电子邮件:

select id
group by email
having count(*)>1

这导致:

更新结果

1

然后我添加了delete子句:

delete from users
where id in(
    select id
    group by email
    having count(*)>1 )

结果是没有错误,但是 0 行受到影响...这意味着什么都没有发生。

我想知道我做错了什么以及其他一些方法。

规格:MySQL 5.5.5-10.1.16-MariaDB 在 Mac

上使用 Sequel Pro

谢谢

您可以执行 sub-query 以获取重复的 id,然后将其从 table 中删除。在此处查看演示: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
      );

已在 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