MySQL对数据去重的方法

 

在使用 MySQL 存储数据的时候,经常会遇到 table 中存在重复数据的情况,这个时候,我们就对 table 进行去重,我这里对常用的 MySQL 去重方法做一个简单的总结。

distinct

select distinct key from table

select distinct key1, key2 from table

语法非常简单,就是针对 table 进行去重操作,统计出所有不同的 key ,并将结果返回;如果传入两个 key 的时候,除去的仅仅是两个 key 都相同的部分。而且这条 sql 并不会对 table 产生修改,只会返回目标数据key(其他字段的数据也不会返回)

利用 group 进行去重

select key from table group by key having count(*)>1

查询单个字段重复数据

select * from table t where(t.key1,t.key2)in(select key1,key2 from table group by key1,key2 having count(*)>1);

查询多个字段的重复数据,并将结果的所有字段信息返回

 

1

2

3

4

5

6

7

8

9

delete from table where key in(

            select t.key from(

                elect key from table group by key having count(*)>1

            )

        )and id not in(

            select t.id from(

                select max(id) as id from table group by id having count(*)>1

            )

        )

删除 table 中重复数据,其实这个思路很简单,对 table 按 key 进行分组统计并计数,将 count 大于 1 的组,仅保留 id 最大的那条数据,其余全部删除。id 一般是主键。

版权声明:本文为lizecheng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/lizecheng/p/14655873.html