sql去除重复数据

OKX欧易app

OKX欧易app

欧易交易所app是全球排名第一的虚拟货币交易所,注册领取6万元盲盒礼包!

APP下载   官网注册


表结构:exhibition_orders表有三个属性:id,student_id, exhibition_id。需求:相同(student_id, exhibition_id) 保留最小id的一条数据。分析思路查找所有的重复数据 ,设为X查找所有的重复数据中最小的一行数据,设为Y在X中,排除Y部分数据,就是需要删除的数据

具体步骤

步骤一: 查找所有的重复数据

方法一

select count(*)from exhibition_orders eo         join (select student_id, exhibition_id               from exhibition_orders               group by student_id, exhibition_id               having count(*) > 1) eo2 on eo2.student_id = eo.student_id and eo2.exhibition_id = eo.exhibition_id

方法二

select count(*)from exhibition_orderswhere (exhibition_id, student_id) in      (select exhibition_id, student_id from exhibition_orders  group by student_id, exhibition_id having count(*)>1) ;
步骤二:重复数据中最小编号
# 重复数据中最小编号select count(*)from exhibition_orderswhere id in      (select min(id) from exhibition_orders  group by student_id, exhibition_id having count(*)>1) ;


步骤三:查询中需要删除的数据

在X中,排除Y部分数据,就是需要删除的数据

select count(*) from exhibition_orderswhere id in(select idfrom exhibition_orderswhere (exhibition_id, student_id) in      (select exhibition_id, student_id from exhibition_orders  group by student_id, exhibition_id having count(*)>1))and id not in(select idfrom exhibition_orderswhere id in      (select min(id) from exhibition_orders  group by student_id, exhibition_id having count(*)>1))
步骤四:删除

删除表是当前表,记得给表取别名

# 需要删除的数据 delete from exhibition_orderswhere id in(select a.id from (select idfrom exhibition_orderswhere (exhibition_id, student_id) in      (select exhibition_id, student_id from exhibition_orders  group by student_id, exhibition_id having count(*)>1)) as a)and id not in(select b.id from (select idfrom exhibition_orderswhere id in      (select min(id) from exhibition_orders  group by student_id, exhibition_id having count(*)>1)) as b) ;


其他方法

创建唯一索引,源头控制

create unique index exhibition_orders_exhibition_id_student_id_uindex    on exhibition_orders (exhibition_id, student_id);


你还有什么其他方法么?欢迎留言

本站所有软件信息均由用户上传发布,版权归原著所有。如有侵权/违规内容,敬请来信告知邮箱:764327034@qq.com,我们将及时撤销! 转载请注明出处:https://www.ssyg068.com/kuaixun/2036.html

打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2024年06月20日
下一篇 2024年06月20日

相关推荐

  • sql查询重复记录、删除重复记录方法

    查找所有重复标题的记录:SELECT *FROM t_info aWHERE ((SELECT COUNT(*)FROM t_infoWHERE Title = a.Title) > 1)ORDER BY Title DESC一、查找重复记录1.查找全部重复记录Select * From 表 Where 重复字段 In (Select 重复字段 From 表 Group By 重复字段 Having Count(*)>1)

    2024-07-12 07:00:01
    158 0

发表回复

8206

评论列表(0条)

    暂无评论

binance币安交易所
已有2000万用户加入币安交易所

立即下载