mysql查看重复id,使用MySQL查找最近重复的ID

I use to do

SELECT email, COUNT(email) AS occurences

FROM wineries

GROUP BY email

HAVING (COUNT(email) > 1);

to find duplicates based on their email.

But now I'd need their ID to be able to define which one to remove exactly.

The second constraint is: I want only the LAST INSERTED duplicates.

So if there's 2 entries with test@test.com as an email and their IDs are respectively 40 and 12782 it would delete only the 12782 entry and keep the 40 one.

Any ideas on how I could do this? I've been mashing SQL for about a hour and can't seem to find exactly how to do this.

Thanks and have a nice day!

解决方案

Well, you sort of answer your question. You seem to want max(id):

SELECT email, COUNT(email) AS occurences, max(id)

FROM wineries

GROUP BY email

HAVING (COUNT(email) > 1);

You can delete the others using the statement. Delete with join has a tricky syntax where you have to list the table name first and then specify the from clause with the join:

delete wineries

from wineries join

(select email, max(id) as maxid

from wineries

group by email

having count(*) > 1

) we

on we.email = wineries.email and

wineries.id < we.maxid;

Or writing this as an exists clause:

delete from wineries

where exists (select 1

from (select email, max(id) as maxid

from wineries

group by email

) we

where we.email = wineries.email and wineries.id < we.maxid

)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值