最近遇到一个问题,就是使用的rm_user_department的重复数据过多,需要删除重复数据,在网上找的sql,照着写的基本上运行都有错误,现在将自己写的贴出来给大家看看.
rm_user_department 的表结构如图:
select * from rm_user_department
DELETE FROM rm_user_department --这里不能使用别名,如果使用别名会报错 WHERE ( user_id, dep_id, user_type ) IN ( select a.userID,a.depId,a.user_type from ( -- 这里需要套一层a,如果去掉这个a,会报错: You can't specify target table 'rm_user_department' for update in FROM clause SELECT user_id as userID, dep_id as depId, user_type -- COUNT(*) FROM rm_user_department GROUP BY user_id, dep_id, user_type HAVING COUNT(*) > 1 ) a ) AND id NOT IN ( SELECT b.id from ( -- 这里b和上面的a是同理 SELECT MIN(tt.id) AS id FROM rm_user_department tt GROUP BY user_id, dep_id, user_type HAVING COUNT(*) > 1 ) b );
大家使用的时候,只需要将我的代码复制下来,将表名改一下就好啦