MySql 删除重复数据

假设表结构

CREATE TABLE `users` (                          
               `id` int(10) NOT NULL AUTO_INCREMENT,                                  
               `name` char(50) NOT NULL,                              
               PRIMARY KEY (`id`)                                   
             )

一般有两个方法:
1. 是用中间表来实现

   1) 使用 create table like 复制出来一个中间表 ,然后用insert into select 把不重复的表导入到中间表中,然后再用中间表替代旧表。 具体实现如下
  create table tmp_users like users;
  Insert into tmp_users (id, name) select min(`id`), `name`   from users group by name ;
  drop  table users ;
  alter  table  tmp_users rename users;

    2) 使用 create table select 直接复制出来一个含有数据的中间表 然后用中间表替代旧表。 具体实现如下
  create table tmp_users(id, name)  select min(`id`),`name`   from users group by name ;
  truncate table users;
  insert into users select * from tmp_users;
  drop table tmp_users;



以上两种方法的区别就是 create table like 

和 create table select 的区别 ,create table like 复制的表结构包含索引 而 create table select 不包含索引,没有索引对业务影响很大,这个要特别留意的。还有就是create table like 和 create table select 复制的表没有把表的权限给copy过来。要事后从新设置下。数据量大的时候应该选择 create table select ,先倾倒数据事后再为表建立索引。

至于用中间表的数据更新旧表的策略,要么用drop旧表再rename中间表。 要么清空旧表数据再导入中间表数据。数据量大的时候前面方法效率较高。

2. 1)找到要删除的数据 然后删除这些数据。具体实现如下,

 

    delete users as a from users as a,(
         select min(id) as id_temp , name from users group by name having count(name) > 1
     ) as b
     where a.name = b.name and a.id <> b.id_temp;

     加上 having count(name) > 1 可以避免扫描没有重复的记录,提高效率

  2)找到要保留的数据 然后用not in 来删除不再这些数据中的记录。大家很容易就想到如下的sql语句:
     delete from users where id not in ( select min(id) from users group by name ); 但是mysql删 除动作不能带有本表的查询动作,意思是你删除users表的东西不能以users表的信息为条件 所以这个语句会报错,执行不了。只要通过创建临时表作为查询条件。具体实现如下:

delete from users where id not in ( select * from ( select min(id) from users group by name ) as temp );

ps: count(x)会排除字段x为空的情况,加入name中存在null的值,则使用group by having的时候不要用count(name),而是使用count( id )




你可能感兴趣的:(MySql 删除重复数据)