获取postgresql中为int8提供的最大免费ID

时间:2017-04-29 16:21:32

标签: sql postgresql

我有一张表有几个ID的表,如100000,99999,99998,1000,10,5。现在我的要求是获取未使用的最大ID。

示例数据:

CREATE TABLE foo
AS
  SELECT *
  FROM ( VALUES (10000),(9999),(9998),(100),(5),(2) )
    AS t(id);

在上面的情况下,它应该是99997.任何查询以获得这个最大可用ID?

2 个答案:

答案 0 :(得分:3)

我已经使用了lead()函数来降低当前id和下一个id之间的差异。

with ct as
(
    select id, lead(id) over (order by id desc) as nextid
    from foo
)
select   id -1 as next_id
from     ct
where    id - nextid > 1
order by id desc
limit 1;

next_id
-------
 9997

drop table foo;

Rextester here

答案 1 :(得分:1)

一种方法使用left join

select t.id - 1
from t left join
     t tprev
     on t.id = tprev.id + 1
where tprev.id is null
order by t.id desc
limit 1;

另一个使用lag()

select t.id - 1
from (select t.*, lag(id) over (order by id) as prev_id
      from t
     ) t
where prev_id <> id - 1
order by id desc
limit 1;