删除表中某字段重复的记录(只保留一条)


表people 

注:此处默认重复字段为name,测试环境为MySQL5.6.

方法一

思路:
1、以名字来分组,找出各组记录中id最小的记录的id;

2、删除原表中id不在1步中id集合中的

delete from people  

where peo_id not in 
(select * from 
(select min(peo_ID)
 from people a
 group by a.name ) as b
);


方法二
思路:
1、找出name重复记录中的最小id;
2、找出非重复记录的id;
3、将原表中id不在1和2步中的记录删除。
delete  from people 
 where peo_id not in 
(select * from 
  (select min(peo_id)
  from people a
  group by a.name
  having count(1) > 1) as b) 
and
       peo_id not in 
( select * from 
  (select min(peo_id)
  from people a
  group by a.name
  having count(1) = 1) as c);


方法三
思路:
1、创建新表temp;
create table temp as select * from people where 1 != 1;
2、将合适的数据存储到temp;
insert into temp
select * from people where peo_id in
(select * from
(select min(peo_id)
from people
group by name ) as b);
3、将原表中的数据全部删除;
delete from people;
4、将temp中的数据插入到原表中。
insert into people
select * from temp;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值