MySQL中分组取第一条, 以及删除多余的重复记录
2017-01-28 13:33
423 查看
检查重复记录
删除重复记录
其中 a 和 b 两个中间表的作用是, 避免执行时出现 You can't specify target table 'xxxxx' for update in FROM clause 错误
分组按时间正序取第一条记录, 巧妙地使用了not exists
按时间倒序则是
-- 检查重复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)
相关文章推荐
- MySQL max_allowed_packet设置及问题
- MySQL相关文章索引(3)
- mysql加悲观锁后还可以读到的问题
- mysqldb的安装
- 网易MySQL数据库工程师微专业学习笔记(五)
- MySQL入门--MySQL复制技术之主主复制
- mysqldb安装错误
- mysql中的增删改查
- mysql 的 占位符使用 以及一次执行多行sql语句
- MySql中常用转换函数介绍
- mysql 协议的FieldList命令包及解析
- MYSQL数据库命名及设计规范
- mysql基础篇 - 其他基本操作
- mysql基础篇 - 数据库及表的修改和删除
- 免费主机屋空间mysql和mssql数据库备份和还原技巧
- MysQL自学笔记8--索引、存储过程
- MysQL自学笔记8--索引、存储过程
- MysQL自学笔记9--自定义函数
- MySQL 资源大全
- MySQL配置文件my.cnf参数优化和中文详解