查询第一个可用插槽 postgres

query first available slot postgres

我有一个 table 叫 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

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

您可以使用 window 函数:

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 

这为您提供 table 中第一个可用的 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)