PostgreSQL函数用于最后插入的ID

在PostgreSQL中,可以通过使用INSERT语句的RETURNING子句来获取最后插入的ID,这与MS SQL中的SCOPE_IDENTITY()不同。示例展示了如何在当前会话中获取特定表和列的最后一个插入ID。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:PostgreSQL function for last inserted ID

In PostgreSQL, how do I get the last id inserted into a table? 在PostgreSQL中,如何将最后一个id插入表中?

In MS SQL there is SCOPE_IDENTITY(). 在MS SQL中有SCOPE_IDENTITY()。

Please do not advise me to use something like this: 请不要建议我使用这样的东西:

select max(id) from table

#1楼

参考:https://stackoom.com/question/clWF/PostgreSQL函数用于最后插入的ID


#2楼

you can use RETURNING clause in INSERT statement,just like the following 您可以在INSERT语句中使用RETURNING子句,如下所示

wgzhao=# create table foo(id int,name text);
CREATE TABLE
wgzhao=# insert into foo values(1,'wgzhao') returning id;
 id 
----
  1
(1 row)

INSERT 0 1
wgzhao=# insert into foo values(3,'wgzhao') returning id;
 id 
----
  3
(1 row)

INSERT 0 1

wgzhao=# create table bar(id serial,name text);
CREATE TABLE
wgzhao=# insert into bar(name) values('wgzhao') returning id;
 id 
----
  1
(1 row)

INSERT 0 1
wgzhao=# insert into bar(name) values('wgzhao') returning id;
 id 
----
  2
(1 row)

INSERT 0 

#3楼

Try this: 试试这个:

select nextval('my_seq_name');  // Returns next value

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: 如果返回1(或任何序列的start_value),则将序列重置回原始值,并传递false标志:

select setval('my_seq_name', 1, false);

Otherwise, 除此以外,

select setval('my_seq_name', nextValue - 1, true);

This will restore the sequence value to the original state and "setval" will return with the sequence value you are looking for. 这会将序列值恢复到原始状态,“setval”将返回您要查找的序列值。


#4楼

SELECT CURRVAL(pg_get_serial_sequence('my_tbl_name','id_col_name'))

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 这将是当前的会话/连接http://www.postgresql.org/docs/8.3/static/functions-sequence.html


#5楼

See the below example 请参阅以下示例

CREATE TABLE users (
    -- make the "id" column a primary key; this also creates
    -- a UNIQUE constraint and a b+-tree index on the column
    id    SERIAL PRIMARY KEY,
    name  TEXT,
    age   INT4
);

INSERT INTO users (name, age) VALUES ('Mozart', 20);

Then for getting last inserted id use this for table "user" seq column name "id" 然后为了获得最后插入的id,请使用此表“user”seq列名“id”

SELECT currval(pg_get_serial_sequence('users', 'id'));

#6楼

See the RETURNING clause of the INSERT statement. 请参见INSERT语句的RETURNING子句。 Basically, the INSERT doubles as a query and gives you back the value that was inserted. 基本上,INSERT兼作查询并返回插入的值。

### 如何在 PostgreSQL插入数据后获取生成的 IDPostgreSQL 数据库中,可以通过多种方式实现 `INSERT` 操作后返回生成的主键值(通常是序列生成的自增 ID)。以下是几种常见的方法及其具体实现: #### 使用 `RETURNING` 子句 PostgreSQL 提供了一个非常方便的关键字 `RETURNING`,可以直接在执行 `INSERT` 的同时返回指定字段的值。这种方法是最常用的方式之一。 ```sql INSERT INTO public.team(name, introduce, teacher_id) VALUES ('test', 'test_intro', 2) RETURNING id; ``` 上述 SQL 将会把新插入记录的 `id` 值作为查询结果返回[^2]。 --- #### 结合 MyBatis 和 Postgres 序列机制 当使用 MyBatis 进行开发时,可以在 Mapper 文件中通过 `<selectKey>` 配置来自动生成并返回主键值。这种方式适用于需要兼容其他数据库的情况。 Mapper XML 示例如下: ```xml <insert id="insertUser"> <selectKey resultType="int" order="AFTER" keyProperty="pid"> SELECT currval('tbl_user_pid_seq'::regclass) AS pid </selectKey> INSERT INTO tbl_user(name, age) VALUES(#{name}, #{age}) </insert> ``` 这里利用了 PostgreSQL 的 `currval()` 函数来获取当前序列值,并将其赋给对象属性 `pid`[^1]。 --- #### 利用序列函数 `nextval()` 如果希望手动控制序列增长,则可以显式调用 `nextval()` 来预先分配一个唯一标识符,然后再完成实际的数据写入操作。 示例代码片段展示如何结合 `nextval()` 实现这一目标: ```sql INSERT INTO public.team(id, name, introduce, teacher_id) VALUES (nextval('public.team_id_seq'), 'test', 'test_intro', 2); ``` 注意,在这种情况下不会自动触发 `RETURNING` 功能,因此可能还需要额外的一次查询去确认最终的结果集。 --- #### 自定义生成批量导入脚本 针对某些特殊场景下需要动态构建大量插入语句的需求,也可以借助存储过程或者外部工具生成相应的命令串。下面给出一段基于 PL/pgSQL 编写的模板化逻辑用于演示目的: ```plpgsql DO $$ DECLARE sqlInsert TEXT; BEGIN sqlInsert := format( $$SELECT 'INSERT INTO "%s" (%s) VALUES (%L)' AS InsertScript FROM %I$$, tableName, colNames, colValues, tableName); -- 添加条件过滤器或其他修饰项... END $$ LANGUAGE plpgsql; ``` 此部分主要讨论的是更高级别的应用层面设计思路而非单纯解决单条记录回传问题[^4]。 --- 综上所述,推荐优先采用简单高效的 `RETURNING` 方案除非有特别需求才考虑其余替代品方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值