sql 查询重复记录(mysql)

1、单子段(nick_name)

查询所有有重复记录的所有记录

select * from user where nick_name in (select nick_name from user group by nick_name having count(nick_name)>1);

查询出有重复记录的各个记录组中的ID最大的记录

select * from user where id in (select max(id) from user group by nick_name having count(nick_name)>1);

查询出多余的记录,不查出id最小的记录

select * from user where id in (select max(id) from user group by nick_name having count(nick_name)>1);

删除多余的重复记录,只保留id 最小的记录

delete from user where nick_name in (select nick_name from (select nick_name from user group by nick_name having count(nick_name)>1) as tmp1) and id not in (select id from (select min(id) from user group by nick_name having count(nick_name)>1) as tmp2);

2、对字段

查出所有有重复记录的记录

select * from user where (nick_name,password) in (select nick_name,password from user group by nick_name,password where having count(nick_name)>1);

查出有重复记录的各个记录组中ID最大的记录

select * from user where id in (select max(id) from user group by nick_name,password where having count(nick_name)>1);

查处各个重复记录组中多余的鸡柳数据,不查出id最小的一条

select * from user where (nick_name,password) in (select nick_name,password from user group by nick_name,password having count(nick_name)>1) and id not in (select min(id) from user group by nick_name,password having count(nick_name)>1);

删除多有的重复记录,只保留id最小的记录】

delete from user where (nick_name,password) in (select nick_name,password from (select nick_name,password from user group by nick_name,password having count(nick_name)>1) as tmp1) and id not in (select id from (select min(id) id from user group by nick_name,password having count(nick_name)>1) as tmp2);

相关推荐
远歌已逝16 分钟前
维护在线重做日志(二)
数据库·oracle
qq_433099401 小时前
Ubuntu20.04从零安装IsaacSim/IsaacLab
数据库
Dlwyz1 小时前
redis-击穿、穿透、雪崩
数据库·redis·缓存
工业甲酰苯胺3 小时前
Redis性能优化的18招
数据库·redis·性能优化
没书读了4 小时前
ssm框架-spring-spring声明式事务
java·数据库·spring
i道i5 小时前
MySQL win安装 和 pymysql使用示例
数据库·mysql
小怪兽ysl5 小时前
【PostgreSQL使用pg_filedump工具解析数据文件以恢复数据】
数据库·postgresql
武子康5 小时前
Java-06 深入浅出 MyBatis - 一对一模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据仓库·sql·mybatis·springboot·springcloud
wqq_9922502775 小时前
springboot基于微信小程序的食堂预约点餐系统
数据库·微信小程序·小程序
爱上口袋的天空5 小时前
09 - Clickhouse的SQL操作
数据库·sql·clickhouse