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

相关推荐
m0_748237051 小时前
sql实战解析-sum()over(partition by xx order by xx)
数据库·sql
dal118网工任子仪2 小时前
61,【1】BUUCTF WEB BUU XSS COURSE 11
前端·数据库·xss
萌小丹Fighting3 小时前
【Postgres_Python】使用python脚本批量创建和导入多个PG数据库
数据库
青灯文案13 小时前
Oracle 数据库常见字段类型大全及详细解析
数据库·oracle
羊小猪~~3 小时前
MYSQL学习笔记(四):多表关系、多表查询(交叉连接、内连接、外连接、自连接)、七种JSONS、集合
数据库·笔记·后端·sql·学习·mysql·考研
村口蹲点的阿三6 小时前
Spark SQL 中对 Map 类型的操作函数
javascript·数据库·hive·sql·spark
苹果醋37 小时前
golang 编程规范 - Effective Go 中文
java·运维·spring boot·mysql·nginx
暮湫7 小时前
MySQL(1)概述
数据库·mysql
唯余木叶下弦声7 小时前
PySpark之金融数据分析(Spark RDD、SQL练习题)
大数据·python·sql·数据分析·spark·pyspark
fajianchen7 小时前
记一次线上SQL死锁事故:如何避免死锁?
数据库·sql