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

在MS SQL中有SCOPE_IDENTITY()。

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

select max(id) from table

当前回答

Postgres有一个内置的机制,可以在同一个查询中返回id或任何您希望查询返回的内容。 这里有一个例子。假设您创建了一个有两列columnn1和column2的表,并且希望在每次插入后返回columnn1。

# create table users_table(id serial not null primary key, name character varying);
CREATE TABLE
#insert into users_table(name) VALUES ('Jon Snow') RETURNING id;
 id 
----
  1
(1 row)

# insert into users_table(name) VALUES ('Arya Stark') RETURNING id;
 id 
----
  2
(1 row)

其他回答

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

当然,您需要提供表名和列名。

这将用于当前会话/连接 http://www.postgresql.org/docs/8.3/static/functions-sequence.html

其他答案没有显示如何使用return返回的值。下面是一个将返回值插入到另一个表的示例。

WITH inserted_id AS (
  INSERT INTO tbl1 (col1)
  VALUES ('foo') RETURNING id
)

INSERT INTO tbl2 (other_id) 
VALUES ((select id from inserted_id));

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

returning *

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

Postgres有一个内置的机制,可以在同一个查询中返回id或任何您希望查询返回的内容。 这里有一个例子。假设您创建了一个有两列columnn1和column2的表,并且希望在每次插入后返回columnn1。

# create table users_table(id serial not null primary key, name character varying);
CREATE TABLE
#insert into users_table(name) VALUES ('Jon Snow') RETURNING id;
 id 
----
  1
(1 row)

# insert into users_table(name) VALUES ('Arya Stark') RETURNING id;
 id 
----
  2
(1 row)

更好的方法是使用Insert和返回。虽然已经有了相同的答案,我只是想补充一下,如果你想把它保存到一个变量,那么你可以这样做

insert into my_table(name) returning id into _my_id;