【问题标题】:query first available slot postgres查询第一个可用插槽 postgres
【发布时间】:2020-11-23 01:34:32
【问题描述】:

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

【问题讨论】:

    标签: sql postgresql subquery window-functions


    【解决方案1】:

    你可以使用窗口函数:

    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)
    

    【讨论】:

    • 感谢您的回答和建议!与您介绍的其他方法相比,一种方法有什么性能优势吗?
    • @LeonardoSilva:您需要根据真实数据评估性能。我更喜欢第一个解决方案,因为它更简洁。另一方面,第二种解决方案将利用chest(idx) 上的索引,如果你有的话。
    • 此查询为可用索引时返回0失败,如何解决?我又提了一个问题:stackoverflow.com/questions/63315637/…
    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2021-09-07
    • 2019-01-03
    • 2018-01-29
    • 2015-08-15
    • 2015-07-23
    • 1970-01-01
    相关资源
    最近更新 更多