删除表中重复记录且保留一个

create table test1(

   id ;

   name;

   primary key ('id');

-----------------------------------------

ID          NAME

1             A

2             A

3             B

4             B

5             C

6             C

------------------------------------------

需求:

删除表中name值重复的行,并保留重复记录中id值最小的行

解决:

mysql:

DELETE from test1 where name IN(select a.name from (SELECT name from test1 GROUP BY name HAVING count(name) > 1) a) and id not IN(SELECT b.id from (SELECT min(id) as id from test1  GROUP BY name HAVING count(name) > 1) b);

oracle:

DELETE from test1 where name IN(SELECT name from test1 GROUP BY name HAVING count(name) > 1) and id not IN(SELECT min(id) as id from test1  GROUP BY name HAVING count(name) > 1);

注意:

如果在mysql中用oracle写法,会报错:[Err] 1093 - You can't specify target table 'test1' for update in FROM clause(你不能更新指定目标的表在from子句中)

原文地址:https://www.cnblogs.com/badoumi/p/5285804.html