在一张id连续的表中找出缺失的id
有这样一张表:
create table tb_lostid( id number(6,0) primary key not null, name nvarchar2(20) not null )
可以这样给它充值:
insert into tb_lostid select rownum, dbms_random.string('*',dbms_random.value(1,20)) from dual connect by level<10000
然后删掉几条记录,以此来模拟误操作:
delete from tb_lostid where id in (3,107,234,888,907)
误操作发生后,任务是要把缺失的记录找出来,这里有两种解决方案。
一种是反联结方案,这种方案利用id连续的特点以id+1在自身中查找,找不到时则为缺失的id,最后去除尾记录就行了。
select a.id+1 from tb_lostid a where not exists (select null from tb_lostid b where b.id=a.id+1) and a.id<> (select max(id) from tb_lostid)
运行结果:
SQL> select a.id+1 from tb_lostid a where not exists (select null from tb_lostid b where b.id=a.id+1) 2 and a.id<> (select max(id) from tb_lostid); A.ID+1 ---------- 3 107 234 888 907
另外一种左联结方案,它也是利用id+1在自身中找,找不到补空的记录即为要找的记录,最后也要去除尾记录。
select a.id+1 from tb_lostid a left join tb_lostid b on b.id=a.id+1 where b.id is null and a.id<> (select max(id) from tb_lostid)
执行结果:
SQL> select a.id+1 from tb_lostid a left join tb_lostid b on b.id=a.id+1 2 where b.id is null and 3 a.id<> (select max(id) from tb_lostid); A.ID+1 ---------- 3 107 234 888 907
--2020年2月24日--
【推荐】国内首个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)
2016-02-24 转载:XPath基本语法
2016-02-24 爪哇国新游记之三十四----Dom4j的XPath操作