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);

相关推荐
·薯条大王3 小时前
MySQL联合查询
数据库·mysql
morris1315 小时前
【redis】redis实现分布式锁
数据库·redis·缓存·分布式锁
hycccccch5 小时前
Canal+RabbitMQ实现MySQL数据增量同步
java·数据库·后端·rabbitmq
这个懒人6 小时前
深入解析Translog机制:Elasticsearch的数据守护者
数据库·elasticsearch·nosql·translog
Yan-英杰6 小时前
【百日精通JAVA | SQL篇 | 第二篇】数据库操作
服务器·数据库·sql
NineData7 小时前
NineData云原生智能数据管理平台新功能发布|2025年3月版
数据库
百代繁华一朝都-绮罗生8 小时前
检查是否存在占用内存过大的SQL
数据库·sql
吾日三省吾码8 小时前
Python 脚本:自动化你的日常任务
数据库·python·自动化
CZIDC8 小时前
win11 系统环境下 新安装 WSL ubuntu + ssh + gnome 桌面环境
数据库·ubuntu·ssh
直裾8 小时前
Mapreduce的使用
大数据·数据库·mapreduce