在PostgreSQL中,如何将最后一个id插入到表中?
在MS SQL中有SCOPE_IDENTITY()。
请不要建议我使用这样的东西:
select max(id) from table
在PostgreSQL中,如何将最后一个id插入到表中?
在MS SQL中有SCOPE_IDENTITY()。
请不要建议我使用这样的东西:
select max(id) from table
当前回答
请参阅下面的示例
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'));
其他回答
参见INSERT语句的RETURNING子句。基本上,INSERT可兼做查询,并返回插入的值。
你可以在插入查询后使用返回id。
INSERT INTO distributors (id, name) VALUES (DEFAULT, 'ALI') RETURNING id;
和结果:
id
----
1
在上面的例子中,id是auto-increment field。
根据上面@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在内的所有对象。
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)