sql - 查询第一个可用插槽 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
解决方案
您可以使用窗口函数:
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)
推荐阅读
- ruby - ruby 中解析 2020-W9 日期的好方法是什么
- ios - UIAnalyticsGatherMutitouchAnalytics 中的崩溃
- python - pandas join 在第一次迭代后无法在 for 循环中工作
- xamarin.forms - 如何在 MediaPlugin 录制的视频的 PHAsset 中添加录制位置
- mongodb - 为什么不建议在生产中启动一个单独的 MongoDB 实例作为副本集?
- arrays - 验证下拉选择
- c++ - 用于替换其参数中的标识符的宏
- angular - 如何使用令牌将 angular7 连接到 liferay?
- c# - 异步返回多个值
- shell - 如何将批处理迁移到外壳?