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

相关推荐
Hoffer_5 小时前
MySQL 强制索引:USE/FORCE INDEX 用法与避坑
后端·mysql
Hoffer_5 小时前
MySQL 索引核心操作:CREATE/DROP/SHOW
后端·mysql
随风飘的云21 小时前
MySQL的慢查询优化解决思路
数据库
IvorySQL1 天前
PostgreSQL 技术日报 (3月7日)|生态更新与内核性能讨论
数据库·postgresql·开源
赵渝强老师1 天前
【赵渝强老师】金仓数据库的数据文件
数据库·国产数据库·kingbase·金仓数据库
随逸1771 天前
《Milvus向量数据库从入门到实战,手把手搭建语义检索系统》
数据库
神秘的猪头1 天前
🚀 React 开发者进阶:RAG 核心——手把手带你玩转 Milvus 向量数据库
数据库·后端·llm
0xDevNull2 天前
MySQL索引进阶用法
后端·mysql
0xDevNull2 天前
MySQL索引用法
mysql
IvorySQL2 天前
PostgreSQL 技术日报 (3月6日)|为什么 Ctrl-C 在 psql 里让人不安?
数据库·postgresql·开源