本文链接:https://blog.csdn.net/zhang168/article/details/30071759
Mysql数据库表中主键不小心去掉,数据导入重复,有好多重复值,好多一模一样的两条(多条)数据,查了半天怎么删除其它的留一条,记录一下。
思路:鉴于2条完全一样的数据,无法区别,只好让他们不一样,于是插入一列自增长的列,需注意的是 自增长列必须是主键
1、给表增加一个自增长的列作为主键,这样的话,完全重复的数据就有了不一样的地方
alter table table_name add column id int(11) PRIMARY KEY AUTO_INCREMENT;
2、删除重复的列中ID较大的那一个
delete from table_name where id in (select id from (select max(id) as id, count(user_role_id) as ucount from table_name group by user_role_id having ucount >1 order by ucount desc) as tab )
3、删除掉新增的主键ID
ALTER table table_name DROP column id;
4、把原来表中的一列设置为主键
ALTER table table_name add PRIMARY KEY (user_role_id)
delete from table_name where id in (select id from (select max(id) as id, count(user_role_id) as ucount from table_name group by user_role_id having ucount >1 order by ucount desc) as tab )