服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Mysql - MySQL 数据查重、去重的实现语句

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

2021-02-04 17:32新码农 Mysql

这篇文章主要介绍了MySQL 数据查重、去重的实现语句,帮助大家更好的理解和学习MySQL数据库,感兴趣的朋友可以了解下

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

一、单字段(nick_name)

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

?
1
select * from user where nick_name in (select nick_name from user group by nick_name having count(nick_name)>1);

查出有重复记录的各个记录组中id最大的记录

?
1
select * from user where id in (select max(id) from user group by nick_name having count(nick_name)>1);

查出多余的记录,不查出id最小的记录

?
1
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最小的记录

?
1
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)

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

?
1
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最大的记录

?
1
select * from user where id in (select max(id) from user group by nick_name,password where having count(nick_name)>1);

查出各个重复记录组中多余的记录数据,不查出id最小的一条

?
1
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最小的记录

?
1
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 数据查重、去重的实现语句的详细内容,更多关于MySQL 数据查重、去重的资料请关注服务器之家其它相关文章!

原文链接:https://www.addcoder.com/blog/article_detail/edbhoezw/

延伸 · 阅读

精彩推荐