从子查询结果中删除id

时间:2018-04-11 17:38:40

标签: mysql sql mariadb sql-delete delete-row

假设我有这个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 )

结果是No Errors,但0行受影响......这意味着什么也没发生。

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

规格:MySQL 5.5.5-10.1.16-MariaDB 在Mac上使用Sequel Pro

由于

2 个答案:

答案 0 :(得分:0)

您可以执行子查询以获取具有重复的id或ID,然后将其从表中删除。请参阅此处的演示: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
      );

答案 1 :(得分:0)

在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