【mysql】sql删除多个字段重复数据有主键和没主键解决方法

时间:2022-04-28 15:08:01

table user
     name age nub
     张三    12  23
     张三    12  23
     张三    12  23
     李四    13  21
     李四    13  21
     王五    11  25

查询重复记录(一条)
sql:select * from user group by name,age,nub having count(*)>1;
    (如需统计条数请使用conut)

set:
     name age nub
     张三   12  23
     李四   13  21

查询重复记录(所有)

sql:select * from user  a where (a.name,a.age,a.nub)  in (select *  from user group by name,age,nub having count(*)>1);

set
     name age nub
     张三   12   23
     张三   12  23
     张三   12  23
     李四   13  21
     李四   13  21

删除重复记录保留一条
 步骤:
     1.将查询的数据插入一个新的表中;
     2.删除原来的表的数据
     3.将新表的数据再插入原表中
     4,删除新表

 sql:
     1. create table new_table (select * from user group by name,age,nub having count(*)>1);
 
     2.delete from user  a where (a.name,a.age,a.nub)  in 
       (select * from 
       (select *  from user group by name,age,nub having count(*)>1) as b );

       在这里使用了两次select 因为:

       delete from user  a where (a.name,a.age,a.nub)  in 
       (select *  from user group by name,age,nub having count(*)>1);会出现错误     
 

       不能对同一表子查询后进行插入或者删除 要在子查询再嵌套一个查询 让对该表查询成为孙查询; 


注:这里更正一下,我按照上面的无法执行,要去除a才可以,如下:

delete from user  where (name,age,nub)  in 
       (select * from 
       (select *  from user group by name,age,nub having count(*)>1) as b );



 
     3.insert into user (select name,age,nub from new_table);
  
      注意:在插入数据的时候查询表得到字段的顺序要与原表相同否者会出现数据错误;
      如果原表数据顺序与新表相同可以用这条语句insert into user (select * from new_table);

     4.drop table new_table;


到此完成操作 最后的数据:


     table user

          name age nub
          张三   12   23
          李四   13   21
          王五   11   25


如果原表中含有主键的话更好操作
 不用四条sql语句了 直接执行删除操作
 delete from user  a where (a.name,a.age,a.nub)  in 
   (select name,age,nub from 
   (select *  from user group by name,age,nub having count(*)>1) as b  )
   and id not in(select min(id) from 
   (select *  from user group by name,age,nub having count(*)>1) as c);

 

注意事项: 在使用 (name,age,address) in (select *)的时候 * 只能是三列 如果有更多列则
不能使用 *,要明确指出是哪些列;