应用在使用过程中发现数据表中有一些重复记录,现需要根据 taobao_nick, taobao_id 来过滤出重复记录并删除,保留其中一条记录即可。
1. 首先使用查询语句检查一下重复记录数
select taobao_nick, taobao_id, count(*) from user group by taobao_nick, taobao_id having count(*) > 1;
2. 使用以下语句删除数据
DB2和Oracle:
delete from user where id in (select max(ID) as id from user group by taobao_nick, taobao_id having count(*) > 1)
如需要删除id较小的记录,可以将max函数修改为min函数。
MySQL:
当在MySQL中使用使用上面的语法时,返回异常 [Err] 1093 - You can't specify target table 'user' for update in FROM clause。修改为下面的语法后可以正常运行。
delete from a using user as a,user as b where a.id>b.id and a.taobao_id = b.taobao_id
如需要删除id较小的记录,可以将 a.id>b.id 修改为 a.id<b.id