删除数据库中重复数据

时间:2021-09-06 04:43:57

数据完全一致的情况:

  #MySQL不支持INTO

  Create table temp (Select DISTINCT * from student);
  DROP TABLE student;
  Create table student (Select * from temp);
  DROP TABLE temp;

  #其他数据库
  SELECT DISTINCT * INTO temp FROM student;
  DROP TABLE student;
  SELECT * INTO student FROM temp;
  DROP TABLE temp;

个别字段一致:

DELETE FROM student WHERE id in (SELECT id FROM (SELECT id FROM student where id not in(SELECT MIN(id) id from student GROUP BY `name`)) as s1);

解析:

因为MySQL不能对同一个表,查询的同时进行更新,所以很多同学都会觉得这个问题比较简单。

SELECT id FROM student where id not in(SELECT MIN(id) id from student GROUP BY `name`);

上面的sql是先查询出所有有效数据,然后通过not in() 的方式找出需要删除的id,最后对结果进行一次包装,起一个别名,然后就可以正常删除了。

删除数据库中重复数据