在使用数据库的时候,由于各种原因可能导致数据库内容重复,在少量重复数据的时候,可以人工排查,或者逐一自动化排查删除,

我遇到的情况是在300K+的数据库中有7K+的重复数据,逐一操作比较耗时。

参考runoob网站的操作,

CREATE TABLE tmp SELECT last_name, first_name, sex FROM person_tbl  GROUP BY (last_name, first_name, sex);
DROP TABLE person_tbl;
ALTER TABLE tmp RENAME TO person_tbl;


第一步: 执行遇到的情况是,我设置了自增加的DataBaseNO作为PRIMARY KEY,此时只能抛弃该字段,只能取有效的字段,而且只能是去重的字段。 第二步:在新创建的tmp 表格中增加自增加的DatabaseNO 作为PRIMARY KEY, 一直无法成功,有大神可以备注一下看如何添加


ALTER TABLE 政府采购网数据.tmp ADD DataBaseNO INT UNSIGNED auto_increment NOT NULL;


SQL 错误 [1075] [42000]: Incorrect table definition; there can be only one auto column and it must be defined as a key
  Incorrect table definition; there can be only one auto column and it must be defined as a key
  Incorrect table definition; there can be only one auto column and it must be defined as a key


由于第二步的不成功,所以再看如何将数据复制到原来的表中,


1)删除原表中的是数据

2)拷贝临时表中的数据

DELETE FROM person_tbl
INSERT INTO person_tbl(last_name, first_name, sex )  SELECT last_name, first_name, sex  FROM tmp;

以上操作后,由于数据库中序号自增,如果解决这个问题可以删除数据库,重建数据库,序号可以从1开始。

操作参考:MySQL 处理重复数据 | 菜鸟教程