从子查询结果中删除id

icnyk63a  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(439)

假设我有这个 users 表格:

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行受影响。。。也就是说什么都没发生。
我想知道我做错了什么,还有其他的方法。
规范:MySQL5.5.5-10.1.16-mariadb在mac上使用sequel pro
谢谢

r6hnlfcb

r6hnlfcb1#

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

cwtwac6a2#

您可以执行子查询来获取一个或多个具有重复id的id,然后将其从表中删除。请参见此处的演示:http://sqlfiddle.com/#!2011年9月14日

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
      );

相关问题