记录一次mysql处理重复数据

该文描述了如何使用SQL查询来找出并处理数据库中reportid重复的数据。首先,它查询出有重复reportid的记录,然后找出这些重复组内odate最大或id最大的记录,最后执行删除操作,保留每个reportid组内的最大odate或最大id记录。
摘要由CSDN通过智能技术生成
// 查询reportid重复的数据
select reportid,count(*) from tables GROUP BY reportid HAVING count(*)>1
// 查询reportid重复的数据中最大操作时间的id数据
select t1.id,t1.reportid,t1.odate from tables t1 INNER JOIN (select reportid,max(odate) max_odate from tables GROUP BY reportid HAVING count(*)>1) t2 on t1.reportid=t2.reportid and t1.odate=t2.max_odate
// 删除重复数据,保留分组时odate最大的一条数据
delete from tables where reportid in ( select t.reportid from (select reportid,count(*) from tables GROUP BY reportid HAVING count(*)>1) t) and id not in (select t2.id from (select t1.id,t1.reportid,t1.odate from tables t1 INNER JOIN (select reportid,max(odate) max_odate from tables GROUP BY reportid HAVING count(*)>1) t2 on t1.reportid=t2.reportid and t1.odate=t2.max_odate) t2)

// 删除重复数据保留id最大的一条
delete from tables where reportid in ( select t.reportid from (select reportid,count(*) from tables GROUP BY reportid HAVING count(*)>1) t) and id not in (select t2.id from (select max(id) id,reportid,count(*) from tables GROUP BY reportid HAVING count(*)>1) t2)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值