MySQL中分组取第一条, 以及删除多余的重复记录

检查重复记录

-- 检查重复code1
select count(identity) num, identity from event_log 
where code='code1' 
group by identity having count(identity) > 1
order by num desc

删除重复记录

DELETE FROM event_log WHERE `code`='code1' AND identity IN (
    SELECT identity from (
        SELECT identity FROM event_log WHERE code='code1' GROUP BY identity HAVING count(identity) > 1
    ) a
) AND id NOT IN (
    SELECT keepId FROM (
        SELECT min(id) keepId FROM event_log WHERE code='code1' GROUP BY identity HAVING count(identity) > 1
    ) b
)

其中 a 和 b 两个中间表的作用是, 避免执行时出现  You can't specify target table 'xxxxx' for update in FROM clause 错误

 

分组按时间正序取第一条记录, 巧妙地使用了not exists

select d.* from t_charge d where not exists (select 1 from t_charge where user_id = d.user_id and created_at < d.created_at)

按时间倒序则是

select f.* from t_charge f where not exists (select 1 from t_charge where user_id = f.user_id and created_at > f.created_at) 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值