一句Delete..In.. 删除语句的优化
实验环境:
# | 类别 | 版本 |
1 | 操作系统 | Win10 |
2 | 数据库 | Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production |
3 | 硬件环境 | T440p |
4 | 内存 | 8G |
建表:
CREATE TABLE tb_sc ( id NUMBER not null primary key, studentid int not null, courseid int not null, score int not null )
充值:
Insert into tb_sc select rownum,dbms_random.value(0,10000),dbms_random.value(1,5),dbms_random.value(0,150) from dual connect by level<=10000 order by dbms_random.random
待优化的SQL,此sql在数据量大时如僵死一般:
delete from tb_sc where (studentid,courseid,score) not in (select studentid,courseid,max(score) as score from tb_sc group by studentid,courseid);
优化方案1:
delete from tb_sc where id not in (select tb_sc.id from tb_sc,( select studentid,courseid,max(score) as score from tb_sc group by studentid,courseid ) tb_sc2 where tb_sc.studentid=tb_sc2.studentid and tb_sc.courseid=tb_sc2.courseid and tb_sc.score=tb_sc2.score)
优化方案2:
delete from tb_sc where not exists ( select null from tb_sc a, (select studentid,courseid,max(score) as score from tb_sc group by studentid,courseid) b where a.studentid=b.studentid and a.courseid=b.courseid and a.score=b.score and tb_sc.id=a.id)
优化方案3: 这种方案适用于delete语句太简单而删除数据较多的场合:
每次删除一百条:
delete from tb_sc where (studentid,courseid,score) not in (select studentid,courseid,max(score) as score from tb_sc group by studentid,courseid) and rownum<101
放在循环里执行:
while(剩余数量>0){ 删除符合条件的 }
优化方案四:将要保留的数据存入一张临时表,删除原表再倒回来,这种操作最大的优势在于降低表的水位线。
相关帖子:
https://www.cnblogs.com/xiandedanteng/p/12232822.html
https://www.cnblogs.com/xiandedanteng/p/12232485.html
https://www.cnblogs.com/xiandedanteng/p/12231995.html
--2020年2月5日--
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2014-02-05 【高中数学/排列组合】我国古代将“礼乐射御书数”合称六艺,某校国学社团计划开展六艺讲座活动,要求活动当天每一艺安排一节,连拍六节,且数必须排在第三节,射和御相邻,则不同的安排顺序共有几种?