2013-02-14 26 views
26

如何在postgresql 8.4中获取当前序列值?检索当前(在运行查询的时刻)序列值的选项

注意:我需要某种统计数据的值,只需检索并存储。在手动递增的情况下,与并发和竞争条件没有任何关系与问题无关。

注2:序列跨越多个表共享

注3:

  • 返回nextval抓到的这个序列在当前会话中最近得到的值:currval不会因为工作
  • ERROR: currval of sequence "<sequence name>" is not yet defined in this session

我现在的想法:是解析DDL,这是奇怪的

+0

你知道该序列的名字吗?你是否需要同时使用序列来担心多个会话? – 2013-02-15 00:02:06

+0

@mu太短:是的,序列名是已知的。而且我需要在我的代码运行时刻的实际值。 – zerkms 2013-02-15 00:03:17

+0

您可能正在寻找['currval'](http://www.postgresql.org/docs/current/static/functions-sequence.html)作为Bohemian的更新说明。 – 2013-02-15 00:05:34

回答

54

您可以使用:

SELECT last_value FROM sequence_name; 

更新: 这是在CREATE SEQUENCE声明中记载:

Although you cannot update a sequence directly, you can use a query like:

SELECT * FROM name;

to examine the parameters and current state of a sequence. In particular, the last_value field of the sequence shows the last value allocated by any session. (Of course, this value might be obsolete by the time it's printed, if other sessions are actively doing nextval calls.)

+0

就是这样!您是否也可以添加对文档的引用,以解释我们可以以这种方式使用序列,然后我会检查您。 – zerkms 2013-02-15 00:13:00

+1

@zerkms:答案更新与参考文档。 – 2013-02-15 00:34:38

+0

很酷,谢谢... – zerkms 2013-02-15 00:58:02

2

如果正在使用的唯一ID在表中的顺序,你可以简单地这样做:

select max(id) from mytable; 

的最有效方式,但具体的Postgres是:

select currval('mysequence'); 

虽然技术上这将返回调用生成的最后一个值到nextval('mysequence'),调用者可能不一定会使用(并且如果未使用会在自动增量id列中留下间隙)。

+0

'max(id)'不能保证接近序列值。 PS:也忘了提及序列在几张桌子上共享,对不起 – zerkms 2013-02-14 23:44:37

+0

为什么downvote?我放弃了使用nax()的免责声明。 – Bohemian 2013-02-15 00:03:32

+0

PS:我没有downvote它(upvote使它回到零) – zerkms 2013-02-15 00:03:44