postgresql - 从插入中选择

标签 postgresql

是否可以从插入语句中进行选择?例如:

SELECT id FROM (INSERT INTO table (col1, col2) VALUES (val1, val2));

其中 id 是一个自动递增的主键。

最佳答案

这是不可能的,因为 INSERT 不会为 SELECT 返回虚拟表。但是,您可以使用 currval(regclass) 获取 id 的实际值序列函数为:

SELECT currval('yourTableName_id_seq'::regclass);
 currval 
---------
       1
(1 row)

编辑:

使用RETURNING clause (自 PostgreSQL 8.2 起可用):

INSERT INTO yourTableName (col1, col2) VALUES ('aaa', 'bbb') RETURNING id;
 id 
----
  2
(1 row)

关于postgresql - 从插入中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7105913/

相关文章:

postgresql - 使用 docker-compose 在 postgresql 中启用日志记录

arrays - 使用 json_array_elements(json) 并获取项目排名

sql - 如何在单个 POSTGRESQL 查询中获取列名及其引用类型(即 PRIMARY KEY 和 FOREIGN KEY)?

sql - Integer 和 JSONB 之间的 PostgreSQL UNION 得到错误 : UNION types integer and jsonb cannot be matched

php - 类型 "e"不存在,通过 php codeigniter 中的 Postgresql 连接器进行 Redshift

java - 具有动态方案的 Jpa

postgresql - 将大型数据集加载到 postgresql 时写入错误文件

ruby-on-rails - rails 4.1。 Heroku ActiveRecord::StatementInvalid (PG::UndefinedFunction: ERROR: operator does not exist: numeric - character varying

ruby-on-rails - Rails 试图连接到端口 5432 上的 postgresql,但它配置为 5433

SQL:从具有特定值的连续行中减去