Mysql重复数据只保留一条
song100e 发布于:2022-10-11 15:59 分类:MySQL 有 142 人浏览,获得评论 0 条 标签: group
例如:user 用户表中 username 重复。将username重复的用户查询出来,保留一条数据。
先附上查重的sql以供验证:
select username, count(*) as num from user GROUP BY username HAVING count(*)>1;查询结果为:
接下来,就需要将username重复的用户删除到只剩一条记录。
第一步:查询出重复记录中id最小的记录。
select min(id) id, username from user GROUP BY username HAVING count(*)>1;结果为:
接下来,以此结果为条件,进行关联查询,将重复数据中,id大于上述结果中id的数据删除。就意味着重复数据只保留了一条。也就是保留下来id最小的那条数据。
最终sql:
delete user from user, (select min(id) id, username from user GROUP BY username HAVING count(*)>1) t2 where user.username=t2.username and user.id=t2.id最后通过查重sql验证。重复数据为空。
实现了想要的效果~!
如果是多条件的话,只需要在查询条件中添加多个过滤条件就可以了。
例如:用户名、性别、电话同时重复的记录查重保留一条记录。
delete user from user, (select min(id) id, username from user GROUP BY username, gender, phone HAVING count(*)>1) t2 where user.username=t2.username and user.gender=t2.gender and user.phone=t2.phone and user.id=t2.id至此,结束!!!
赞助我,共同学习进步!

