在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语句中使用return子句,如下所示
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
对于需要获取所有数据记录的用户,可以添加
returning *
到查询的末尾以获取包括id在内的所有对象。
SELECT CURRVAL(pg_get_serial_sequence('my_tbl_name','id_col_name'))
当然,您需要提供表名和列名。
这将用于当前会话/连接 http://www.postgresql.org/docs/8.3/static/functions-sequence.html
我在使用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
请参阅下面的示例
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'));