在PostgreSQL中,如何将最后一个id插入到表中?

在MS SQL中有SCOPE_IDENTITY()。

请不要建议我使用这样的东西:

select max(id) from table

当前回答

根据上面@ooZman的回答,这似乎适用于PostgreSQL v12,当你需要插入一个“序列”的下一个值时(类似于auto_increment),而不会在你的表(s)计数器中搞得很混乱。(注意:我还没有在更复杂的DB集群配置中测试它…)

Psuedo代码

$insert_next_id = $return_result->query("select (setval('"your_id_seq"', (select nextval('"your_id_seq"')) - 1, true)) +1");

其他回答

对于需要获取所有数据记录的用户,可以添加

returning *

到查询的末尾以获取包括id在内的所有对象。

请参阅下面的示例

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);

然后,要获取最后插入的id,请使用下面的语句对user表执行seq列名为id

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

你可以在插入查询后使用返回id。

INSERT INTO distributors (id, name) VALUES (DEFAULT, 'ALI') RETURNING id;

和结果:

 id 
----
  1

在上面的例子中,id是auto-increment field。

我在使用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

根据上面@ooZman的回答,这似乎适用于PostgreSQL v12,当你需要插入一个“序列”的下一个值时(类似于auto_increment),而不会在你的表(s)计数器中搞得很混乱。(注意:我还没有在更复杂的DB集群配置中测试它…)

Psuedo代码

$insert_next_id = $return_result->query("select (setval('"your_id_seq"', (select nextval('"your_id_seq"')) - 1, true)) +1");