查询第一个可用的槽postgres

lp0sw83n  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(337)

我有一张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

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

iyr7buue1#

可以使用窗口函数:

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)

相关问题