MySQL中分组取第一条, 以及删除多余的重复记录
2023-03-07 09:41:49 时间
检查重复记录
-- 检查重复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)
相关文章
- 数据孤岛是业务效率的无声杀手
- 2023展望:新的一年将给大数据分析领域带来什么?
- 阿里云ADB基于Hudi构建Lakehouse的实践
- 大数据在医疗保健领域的使用案例
- 微软增加说明:KB5021751 更新扫描已经 / 即将过时 Office 过程中不会触碰用户隐私
- 2022 Gartner全球云数据库管理系统魔力象限发布 腾讯云数据库入选
- 场景化、重实操,分享一个实时数仓实践案例
- Arctic的湖仓一体践行之路
- 分布式计算MapReduce究竟是怎么一回事?
- 淘系数据模型治理优秀实践
- 大数据分析对医疗保健的影响
- 当我们说大数据Hadoop,究竟在说什么?
- 2022年及以后大数据的五个发展趋势
- 网易严选离线数仓治理实践
- 2023 年数据治理趋势
- 一份“靠谱”的年度经营计划,你学会了吗?
- 漫谈对大数据的思考
- 测试一下,读懂数据的能力,你有吗?
- 用艺术的眼光探索数据之美
- 聊聊数据分析成果如何落地