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

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|

服务器之家 - 数据库 - Mysql - MySQL去重的方法整理

MySQL去重的方法整理

2020-08-01 17:46starglm Mysql

这篇文章主要介绍了MySQL去重的方法整理的相关资料,需要的朋友可以参考下

MySQL去重的方法整理

【初级】有极少的重复行

使用distinct查出来,然后手动一行一行删除。

【中级】按照单个字段的重复去重

例如:对id字段去重

使用方法:获取id的重复字段的值,利用相同id字段所在的行中,比较出数据不同的字段,删除 除了最小(或最大)的字段所在的该行之外的所有重复的行。一般使用主键来比较,因为主键的值一定是唯一值,绝对不相同。

?
1
2
3
4
5
6
7
8
9
10
11
id  name
 
1    a
 
1    b
 
2    c
 
2    a
 
3    c

结果:

?
1
2
3
4
5
id  name
 
1    a
 
2    a

操作:

?
1
2
3
4
5
delete from a_tmp
 
where id in (select * from (select b.id from a_tmp b group by b.id having count(b.id) >1) bb)
 
and name not in (select * from (select min(a.name) from a_tmp a GROUP BY a.id having count(a.id) >1) aa);

注意:

上述加粗并绿色的字,必须加别名,必须使用select * from (……)这样的格式,否则会报错:

[Err] 1093 - You can't specify target table 'a_tmp' for update in FROM clause

【高级】按多个字段的重复来去重

例如:对id,name相同的去重,即:对id,name都相同的算作重复行,对id相同而name不同的算作不重复行

使用方法:和单个字段相似,一般使用主键来比较,因为主键的值一定是唯一值。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
id  name  rowid
 
1  a      1
 
1  a      2
 
1  b      3
 
2  b      4
 
2  b      5
 
3  c      6
 
3  d     7

结果:

?
1
2
3
4
5
6
7
8
9
10
11
id  name  rowid
 
1  a      1
 
1  b      3
 
2  b      4
 
3  c      6
 
3  d     7

操作:

第一种:

?
1
2
3
4
5
delete from a_tmp
 
where (id,name) in (select * from (select b.id,b.name from a_tmp b group by b.id,b.name having count(b.id) >1) bb)
 
and rowid not in (select * from (select min(a.rowid) from a_tmp a group by a.id,a.name having count(a.id) >1) aa);

第二种:

将id和name字段的值连接起来插入到临时表中b_tmp,这样便可以使用【中级】的单字段的判断删除方法。

#将两字段连接的值,a_tmp表中唯一值的字段插入b_tmp表

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
insert into b_tmp
 
 select concat(id,name),rowid from a_tmp;
 
#查出需要留下来的行
 
select id_name,max(rowid)
 
 from b_tmp
 
 group by id_name
 
 having count(id_name)>1;
 
#使用【中级】的方法,或存储过程完成去重的工作

 【终极】每行都有两份一样的数据

例如:

使用方法:对于整行的数据都一样,是没办法使用SQL语句删除的,因为没有可以使用的条件限制来留下一行删除所有与其相同的行。没有不同的字段可以自己创造不同的字段,即:添加一个字段,设为自增长,并设为主键,它会自动添加上值。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
id  name
 
1   a
 
1   a
 
1   b
 
1   b
 
2   c
 
2   c
 
3   c
 
3   c

结果:

?
1
2
3
4
5
6
7
8
9
id  name   rowid
 
1   a       1
 
1   b       3
 
2   c       5
 
3   c       7

操作:

添加一个自增长的字段,并暂时设为主键。

使用上面【中级】和【高级】的方法操作。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:https://my.oschina.net/starglm/blog/748701

延伸 · 阅读

精彩推荐