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

相关推荐
天上掉下来个程小白8 分钟前
案例-14.文件上传-简介
数据库·spring boot·后端·mybatis·状态模式
哆木17 分钟前
排查生产sql查询缓慢
数据库·sql·mysql
橘子师兄1 小时前
分页功能组件开发
数据库·python·django
book01212 小时前
MySql数据库运维学习笔记
运维·数据库·mysql
纠结哥_Shrek2 小时前
Oracle和Mysql的区别
数据库·mysql·oracle
极客先躯2 小时前
说说高级java每日一道面试题-2025年2月13日-数据库篇-请说说 MySQL 数据库的锁 ?
java·数据库·mysql·数据库的锁·模式分·粒度分·属性分
做梦敲代码2 小时前
达梦统计信息
数据库·达梦数据库
jiugie2 小时前
MongoDB学习
数据库·python·mongodb
hzulwy2 小时前
MongoDB应用设计调优
数据库·mongodb
我爱松子鱼3 小时前
MySQL 单表访问方法详解
数据库·mysql