MySQL如何删除重复记录
方法有很多,除了最简便的,
alter ignore table 表名 add UNIQUE index(字段名);
然后再将索引drop掉,这个方法外。
更加中规中矩的方法也是有的。。
比如我在网上搜到的:
delete from people
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
and id not in (select min(id) from people group by peopleId having count(peopleId )>1)
这个看起来好像很有道理,但是执行的时候就会报错。。You can't specify target table 'people' for update in FROM clause。
原因就是上面的那一条SQL,删除和查询操作都是针对同一张表的。。MYSQL是不允许这样做滴。
这样就可以了
delete from people
where peopleId in (select peopleId from(select id,peopleId from people) as a group by peopleId having count(peopleId) > 1)
and id not in (select min(id) from (select id,peopleId from people) as b group by peopleId having count(peopleId )>1)
简单一点的可以这样写
delete from id where Id not in (select min(Id) from(selectid,peopleId from people)as a GROUP by peopleId );
粗体部分就是把一张表转换成了一个提取表(derived table),从而解决了问题,需要注意的是后面那个as 别名,不能省略,否则会报错"Every derived TABLE must have its own alias“。