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

相关推荐
尘浮生1 小时前
Java项目实战II基于Spring Boot的火锅店管理系统设计与实现(开发文档+数据库+源码)
java·开发语言·数据库·spring boot·后端·微信小程序·旅游
海波东1 小时前
oracle和mysql的区别常用的sql语句
sql·mysql·oracle
FIN技术铺1 小时前
Redis有什么不一样?
数据库·redis·缓存
华为云开发者联盟1 小时前
遇到慢查询怎么办?一文解读MySQL 8.0查询分析工具
sql·mysql·查询分析·explain analyze
API开发2 小时前
测试华为GaussDB(DWS)数仓,并通过APISQL快速将(表、视图、存储过程)发布为API
数据仓库·sql·postgresql·华为云·api·gaussdb·apisql
苹果醋32 小时前
springboot-springboot官方文档架构
java·运维·spring boot·mysql·nginx
声声codeGrandMaster2 小时前
爬虫+数据保存2
爬虫·python·mysql
Devil枫3 小时前
腾讯云云开发深度解读:云数据库、云模板与AI生成引用的魅力
数据库·人工智能·腾讯云
tatasix3 小时前
MySQL数据库备份与恢复
mysql
Kanna_STELLA3 小时前
Oracle视频基础1.1.4练习
数据库·oracle