PostgreSQL 函数获取最后插入的 ID
在 PostgreSQL 中,如何获取插入表中的最后一个 id?
在 MS SQL 中,有 SCOPE_IDENTITY()。
请不要建议我使用这样的东西:
select max(id) from table
In PostgreSQL, how do I get the last id inserted into a table?
In MS SQL there is SCOPE_IDENTITY().
Please do not advise me to use something like this:
select max(id) from table
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
(
tl;dr
: goto option 3: INSERT with RETURNING )回想一下,在 postgresql 中,表没有“id”概念,只有序列(通常但不一定)用作代理主键的默认值,带有 SERIAL伪类型 - 或者,从版本 10 开始,使用 生成为身份)。
如果您有兴趣获取新插入行的 id,有多种方法:
选项 1:
CURRVAL(<序列名称>);
。例如:
序列的名称必须是已知的,它真的是任意的;在此示例中,我们假设表
persons
具有使用SERIAL
伪类型创建的id
列。为了避免依赖于此并感觉更干净,您可以使用 < code>pg_get_serial_sequence:警告:
currval()
仅在INSERT
后有效(已执行nextval()
),在同一会话中。选项 2:
LASTVAL();
这与前一个类似,只是您不需要指定序列名称:它会查找最近修改的序列(始终在您的会话内,与上面相同的警告)。
CURRVAL
和LASTVAL
都是完全并发安全的。 PG 中序列的行为经过精心设计,以便不同的会话不会干扰,因此不存在竞争条件的风险(如果另一个会话在我的 INSERT 和 SELECT 之间插入另一行,我仍然会得到正确的值)。但是他们确实有一个微妙的潜在问题。如果数据库有一些 TRIGGER (或规则),则在插入时到
persons
表中,在其他表中进行一些额外的插入...然后LASTVAL
可能会给我们错误的值。如果在同一个persons
表中进行额外的插入,则CURRVAL
甚至可能会出现此问题(这种情况不太常见,但风险仍然存在)。选项 3:
INSERT
RETURNING
这是获取 id 的最干净、最高效、最安全的方法。它没有以前的任何风险。
缺点?几乎没有:您可能需要修改调用 INSERT 语句的方式(在最坏的情况下,也许您的 API 或 DB 层不期望 INSERT 返回值);它不是标准 SQL(谁在乎);它从 Postgresql 8.2(2006 年 12 月)开始可用。
结论:如果可以的话,请选择选项 3。在其他地方,更喜欢选项 1。
注意:如果您打算获取全局最后插入的 id,所有这些方法都是无用的。 strong>(不一定是您的会话)。为此,您必须求助于
SELECT max(id) FROM table
(当然,这不会从其他事务中读取未提交的插入)。相反,您应该永远使用
SELECT max(id) FROM table
而不是上面的3个选项之一来获取刚刚由您的INSERT 语句,因为(除了性能之外)这不是并发安全的:在您的
INSERT
和SELECT
之间,另一个会话可能插入了另一条记录。(
tl;dr
: goto option 3: INSERT with RETURNING )Recall that in postgresql there is no "id" concept for tables, just sequences (which are typically but not necessarily used as default values for surrogate primary keys, with the SERIAL pseudo-type - or, since version 10, with GENERATED AS IDENTITY).
If you are interested in getting the id of a newly inserted row, there are several ways:
Option 1:
CURRVAL(<sequence name>);
.For example:
The name of the sequence must be known, it's really arbitrary; in this example we assume that the table
persons
has anid
column created with theSERIAL
pseudo-type. To avoid relying on this and to feel more clean, you can use insteadpg_get_serial_sequence
:Caveat:
currval()
only works after anINSERT
(which has executednextval()
), in the same session.Option 2:
LASTVAL();
This is similar to the previous, only that you don't need to specify the sequence name: it looks for the most recent modified sequence (always inside your session, same caveat as above).
Both
CURRVAL
andLASTVAL
are totally concurrent safe. The behaviour of sequence in PG is designed so that different session will not interfere, so there is no risk of race conditions (if another session inserts another row between my INSERT and my SELECT, I still get my correct value).However they do have a subtle potential problem. If the database has some TRIGGER (or RULE) that, on insertion into
persons
table, makes some extra insertions in other tables... thenLASTVAL
will probably give us the wrong value. The problem can even happen withCURRVAL
, if the extra insertions are done intto the samepersons
table (this is much less usual, but the risk still exists).Option 3:
INSERT
withRETURNING
This is the most clean, efficient and safe way to get the id. It doesn't have any of the risks of the previous.
Drawbacks? Almost none: you might need to modify the way you call your INSERT statement (in the worst case, perhaps your API or DB layer does not expect an INSERT to return a value); it's not standard SQL (who cares); it's available since Postgresql 8.2 (Dec 2006...)
Conclusion: If you can, go for option 3. Elsewhere, prefer 1.
Note: all these methods are useless if you intend to get the last inserted id globally (not necessarily by your session). For this, you must resort to
SELECT max(id) FROM table
(of course, this will not read uncommitted inserts from other transactions).Conversely, you should never use
SELECT max(id) FROM table
instead one of the 3 options above, to get the id just generated by yourINSERT
statement, because (apart from performance) this is not concurrent safe: between yourINSERT
and yourSELECT
another session might have inserted another record.请参阅 INSERT 语句的 RETURNING 子句。基本上,INSERT 兼作查询并返回插入的值。
See the RETURNING clause of the INSERT statement. Basically, the INSERT doubles as a query and gives you back the value that was inserted.
Leonbloy的答案非常完整。我只会添加一种特殊情况,即需要从 PL/pgSQL 函数中获取最后插入的值,而选项 3 并不完全适合。
例如,如果我们有下表:
如果我们需要插入客户记录,我们必须引用人员记录。但是,假设我们想要设计一个 PL/pgSQL 函数,它将新记录插入客户端,同时也负责插入新人员记录。为此,我们必须使用 leonbloy 的选项 3 的细微变化:
请注意,有两个 INTO 子句。因此,PL/pgSQL 函数的定义如下:
现在我们可以使用以下命令插入新数据:
或
我们得到新创建的 id。
Leonbloy's answer is quite complete. I would only add the special case in which one needs to get the last inserted value from within a PL/pgSQL function where OPTION 3 doesn't fit exactly.
For example, if we have the following tables:
If we need to insert a client record we must refer to a person record. But let's say we want to devise a PL/pgSQL function that inserts a new record into client but also takes care of inserting the new person record. For that, we must use a slight variation of leonbloy's OPTION 3:
Note that there are two INTO clauses. Therefore, the PL/pgSQL function would be defined like:
Now we can insert the new data using:
or
And we get the newly created id.
其他答案没有显示如何使用
RETURNING
返回的值。下面是一个将返回值插入到另一个表中的示例。The other answers don't show how one might use the value(s) returned by
RETURNING
. Here's an example where the returned value is inserted into another table.您可以在 INSERT 语句中使用 RETURNING 子句,如下所示
you can use RETURNING clause in INSERT statement,just like the following
请参阅下面的示例
然后,为了获取最后插入的 id,请将其用于表“user”seq 列名称“id”
See the below example
Then for getting last inserted id use this for table "user" seq column name "id"
当然,您需要提供表名和列名。
这将用于当前会话/连接
http://www.postgresql.org/docs/8.3/static/functions -sequence.html
You need to supply the table name and column name of course.
This will be for the current session / connection
http://www.postgresql.org/docs/8.3/static/functions-sequence.html
您可以在插入查询后使用 RETURNING id。
结果:
在上面的例子中,id是自增字段。
You can use RETURNING id after insert query.
and result:
In the above example id is auto-increment filed.
对于需要获取所有数据记录的人,可以添加
到查询的末尾以获取包括id的所有对象。
For the ones who need to get the all data record, you can add
to the end of your query to get the all object including the id.
更好的方法是使用 Insert 并返回。虽然已经有相同的答案,但我只是想补充一点,如果你想将其保存到变量中,那么你可以这样做
The better way is to use Insert with returning. Though there are already same answers, I just want to add, if you want to save this to a variable then you can do this
Postgres 有一个内置的机制,它在同一个查询中返回 id 或您希望查询返回的任何内容。
这是一个例子。假设您创建了一个包含 2 列(column1 和 column2)的表,并且您希望在每次插入后返回 column1。
Postgres has an inbuilt mechanism for the same, which in the same query returns the id or whatever you want the query to return.
here is an example. Consider you have a table created which has 2 columns column1 and column2 and you want column1 to be returned after every insert.
试试这个:
如果返回 1(或者序列的 start_value 是什么),则将序列重置回原始值,传递 false 标志:
否则,
这会将序列值恢复到原始状态,并且“setval”将返回您要查找的序列值。
Try this:
If this return 1 (or whatever is the start_value for your sequence), then reset the sequence back to the original value, passing the false flag:
Otherwise,
This will restore the sequence value to the original state and "setval" will return with the sequence value you are looking for.
我在使用 Java 和 Postgres 时遇到了这个问题。
我通过更新新的 Connector-J 版本修复了该问题。
postgresql-9.2-1002.jdbc4.jar
https://jdbc.postgresql.org/download.html:
版本 42.2.12
https://jdbc.postgresql.org/download/postgresql- 42.2.12.jar
I had this issue with Java and Postgres.
I fixed it by updating a new Connector-J version.
postgresql-9.2-1002.jdbc4.jar
https://jdbc.postgresql.org/download.html:
Version 42.2.12
https://jdbc.postgresql.org/download/postgresql-42.2.12.jar