postgresql 检索当前(在运行查询的时刻)序列值的选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14886048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:02:38  来源:igfitidea点击:

Options to retrieve the current (on a moment of running query) sequence value

postgresqlpostgresql-8.4

提问by zerkms

How is it possible to get the current sequence value in postgresql 8.4?

如何在 postgresql 8.4 中获取当前序列值?

Note: I need the value for the some sort of statistics, just retrieve and store. Nothing related to the concurrency and race conditions in case of manually incrementing it isn't relevant to the question.

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

Note 2: The sequence is shared across several tables

注 2:序列在多个表之间共享

Note 3: currvalwon't work because of:

注 3:currval将无法工作,因为:

  • Return the value most recently obtained by nextval for this sequence in the current session
  • ERROR: currval of sequence "<sequence name>" is not yet defined in this session
  • 返回当前会话中此序列的 nextval 最近获得的值
  • ERROR: currval of sequence "<sequence name>" is not yet defined in this session

My current idea: is to parse DDL, which is weird

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

回答by Daniel Vérité

You may use:

您可以使用:

SELECT last_value FROM sequence_name;

Update: this is documented in the CREATE SEQUENCEstatement:

更新:这记录在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_valuefield 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.)

虽然您不能直接更新序列,但您可以使用如下查询:

选择 * 从名称;

检查序列的参数和当前状态。特别是,序列的last_value字段显示了任何会话分配的最后一个值。(当然,如果其他会话正在主动进行 nextval 调用,则该值在打印时可能已过时。)

回答by Bohemian

If the sequence is being used for unique ids in a table, you can simply do this:

如果序列用于表中的唯一 ID,您可以简单地执行以下操作:

select max(id) from mytable;

The most efficient way, although postgres specific, is:

尽管特定于 postgres,但最有效的方法是:

select currval('mysequence');

although technically this returns the last value generated by the call to nextval('mysequence'), which may not necessarily be usedby the caller (and if unused would leave gaps in an auto increments id column).

尽管从技术上讲,这会返回调用生成的最后一个值,调用者nextval('mysequence')可能不一定会使用它(如果未使用,则会在自动增量 id 列中留下空白)。