首页 > 解决方案 > Count Number SQL where 不存在

问题描述

是否可以选择获取表格中不存在的数字?

例子

product_number
1
2
3
5

我只想要数字 4 作为结果,因为它是免费的产品编号。
问题是通过 rownum 连接不起作用,因为内存不足。

标签: sqloracleplsql

解决方案


由于您没有提供真实产品编号的样本(显然),但声称连接内存不足可能意味着您的产品编号非常大。因此,需要将需要检查的数量限制在已知可能存在的范围内,即最小和最大产品编号。一旦知道了,我们就可以生成产品编号的索引,以查看特定编号是否存在,或者其中不存在。所以:

with lh  as 
     (select min(product_number) l  
           , max(product_number) h 
       from products
     )  
   , range (pn) as
      (select product_number pn 
         from products 
        where product_number = (select l from lh)
       union all 
       select pn + 1 
         from range 
        where pn + 1 <= (select h from lh)
      )  
select pn available_product_number
  from range
 where not exists
     ( select null 
       from products
      where pn = product_number
     )
order by pn;

推荐阅读