假设我们的一个student表,其中有元素
id、name、age。
一般我们数据库中重复数据有两种情况。
一:所以元素全部相同的情况。
对于这种情况,我们可以用下面的命令,解决。
select distinct * from student;
二:部分元素相同的情况。
现在假设我们需要删除name、age重复的元素,
保留重复数据中的最小id。
步骤一:找出name和age,都重复数据中的最小id元素。
select min(id) id from student where name is not null group by name,age having count(1) > 1;
步骤二:找出name或者age,没有重复的元素。
select id from student where name is not null group by name,age having count(1) = 1;
步骤三:删除除了我们步骤一、二中找到的元素之外的元素。(注意这里需要将我们查询出来的元素给另外一个表再删除,不然在mysql下会报错)下面是完整命令。
delete from student where id not in ( select t.id from (
select min(id) id from student where name is not null group by name,age having count(1) > 1 union
select id from student where name is not null group by name,age having count(1) = 1) t);