获取表中第一个可用索引,包括0
Posted
技术标签:
【中文标题】获取表中第一个可用索引,包括0【英文标题】:Get first available index in the table, including 0 【发布时间】:2020-08-08 12:53:33 【问题描述】:我有一个名为player_chest
的表,其中包含以下字段:
idx integer NOT NULL,
player_id integer NOT NULL,
chest_id integer NOT NULL,
我正在使用以下查询来获取表中的第一个可用索引:
SELECT c.idx + 1 FROM player_chest c WHERE c.player_id = 2 AND NOT EXISTS (
SELECT 1 FROM player_chest c1 WHERE c1.player_id = 2 AND c1.idx = c.idx + 1
) ORDER BY c.idx;
查询工作的示例:
chest_id | idx | player_id
0 | 0 | 2
1 | 1 | 2
2 | 2 | 2
1 | 4 | 2
返回 3
查询不工作的示例: 查询工作的示例:
chest_id | idx | player_id
1 | 1 | 2
2 | 2 | 2
1 | 4 | 2
返回 3,但我希望它返回 0
但它在可用时无法返回索引 0。我该如何解决?
【问题讨论】:
样本数据和期望的结果会有所帮助。 我添加了示例数据 【参考方案1】:一种解决方案使用窗口函数:
select (case when min_idx > 0 then 0
else 1 + min(idx) filter (where next_idx is distinct from idx + 1)
end)
from (select pc.*,
lead(idx) over (partition by player_id order by idx) as next_idx,
min(idx) over (partition by player_id) as min_idx
from player_chest pc
where player_id = 2
) pc
group by player_id, min_idx;
如果你想要一个即使玩家不在桌子上也能返回0
的版本,那么:
select (case when max(min_idx) > 0 or max(min_idx) is null then 0
else 1 + min(idx) filter (where next_idx is distinct from idx + 1)
end)
from (select pc.*,
lead(idx) over (partition by player_id order by idx) as next_idx,
min(idx) over (partition by player_id) as min_idx
from player_chest pc
where player_id = 2
) pc
【讨论】:
你的意思是如果玩家在 player_chest 表中没有条目,那么只有第二个查询会起作用?以上是关于获取表中第一个可用索引,包括0的主要内容,如果未能解决你的问题,请参考以下文章