登录
首页 >  数据库 >  MySQL

MySQL 数据查重、去重的实现语句

来源:脚本之家

时间:2023-01-08 13:29:00 479浏览 收藏

在数据库实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《MySQL 数据查重、去重的实现语句》,聊聊去重、MySQL数据、查重,希望可以帮助到正在努力赚钱的你。

有一个表user,字段分别有id、nick_name、password、email、phone。

一、单字段(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 nick_name in (select nick_name from user group by nick_name having count(nick_name)>1) and id not in (select min(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);

二、多字段(nick_name,password)

查出所有有重复记录的记录

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

本篇关于《MySQL 数据查重、去重的实现语句》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于数据库的相关知识,请关注golang学习网公众号!

声明:本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表