在一张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日--

posted @   逆火狂飙  阅读(570)  评论(0编辑  收藏  举报
编辑推荐:
· 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操作
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东
点击右上角即可分享
微信分享提示