首页 > 解决方案 > 查询第一个可用插槽 postgres

问题描述

我有一张桌子叫chest

chest_id integer NOT NULL
index integer NOT NULL

我可以通过查询获得下一个索引

select max(index) + 1 from chest group by chest_id

如果订单中有一些索引没有被填写,如何获取呢?例如:

chest_id | index
       0 |     0
       1 |     1
       2 |     2
       1 |     4

我将如何查询以返回第一个可用索引?在上面的例子中,它是 3。但如果它被填满,下一个可用的也是 5

标签: sqlpostgresqlsubquerywindow-functions

解决方案


您可以使用窗口函数:

select idx + 1
from (select idx, lead(idx) over(order by idx) lead_idx from chest) t
where idx + 1 is distinct from lead_idx 

这为您提供idx表中的第一个可用值(差距或最大值 + 1)。

请注意,这index是一个语言关键字,因此不是列名的好选择。我将其重命名为idx.

另一种选择是not exists

select c.idx + 1
from chest c
where not exists (select 1 from chest c1 where c1.idx = c.idx + 1)

推荐阅读