Sql 获取表中第一个可用索引,包括0

Sql 获取表中第一个可用索引,包括0,sql,postgresql,Sql,Postgresql,我有一个名为player_cost的表,它有以下字段: idx整数不为空, 玩家id整数不为空, 胸部id整数不为空, 我使用以下查询获取表中的第一个可用索引: 从播放器c中选择c.idx+1,其中c.player\u id=2且不存在 从player_胸部c1中选择1,其中c1.player_id=2和c1.idx=c.idx+1 c.idx订购; 查询工作的示例: chest_id | idx | player_id 0 | 0 | 2 1 |

我有一个名为player_cost的表,它有以下字段:

idx整数不为空, 玩家id整数不为空, 胸部id整数不为空, 我使用以下查询获取表中的第一个可用索引:

从播放器c中选择c.idx+1,其中c.player\u id=2且不存在 从player_胸部c1中选择1,其中c1.player_id=2和c1.idx=c.idx+1 c.idx订购; 查询工作的示例:

chest_id | idx | player_id
       0 |   0 |         2
       1 |   1 |         2
       2 |   2 |         2
       1 |   4 |         2
chest_id | idx | player_id
       1 |   1 |         2
       2 |   2 |         2
       1 |   4 |         2
返回3

查询不起作用的示例: 查询工作的示例:

chest_id | idx | player_id
       0 |   0 |         2
       1 |   1 |         2
       2 |   2 |         2
       1 |   4 |         2
chest_id | idx | player_id
       1 |   1 |         2
       2 |   2 |         2
       1 |   4 |         2
返回3,但我希望它返回0


但当索引0可用时,它无法返回索引0。如何修复它?

一个解决方案使用窗口功能:

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

一种解决方案使用窗口功能:

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

示例数据和期望的结果会有帮助。我添加了示例数据示例数据和期望的结果会有帮助。我添加了示例数据u的意思是如果玩家在player\u chest表中没有条目,那么只有第二个查询可以工作?u的意思是如果玩家在player\u chest表中没有条目,那么只有第二个查询可以工作?