postgresql - 在 Postgres 中输出 Inserted.id 等效项
问题描述
我是 PostgreSQL 新手,正在尝试将 mssql 脚本转换为 Postgres。
对于 Merge 语句,我们可以在冲突更新时使用 insert 或什么都不做,只使用下面的语句,不确定它是否正确。
MSSQL 代码:
Declare @tab2(New_Id int not null, Old_Id int not null)
MERGE Tab1 as Target
USING (select * from Tab1
WHERE ColumnId = @ID) as Source on 0 = 1
when not matched by Target then
INSERT
(ColumnId
,Col1
,Col2
,Col3
)
VALUES (Source.ColumnId
,Source.Col1
,Source.Col2
,Source.Col3
)
OUTPUT INSERTED.Id, Source.Id into @tab2(New_Id, Old_Id);
Postgres代码:
Create temp table tab2(New_Id int not null, Old_Id int not null)
With source as( select * from Tab1
WHERE ColumnId = ID)
Insert into Tab1(ColumnId
,Col1
,Col2
,Col3
)
select Source.ColumnId
,Source.Col1
,Source.Col2
,Source.Col3
from source
我的查询是如何在 postgres 中转换 OUTPUT INSERTED.Id。我需要这个 id 在另一个表中插入记录(可以说是基于 Tab1 中插入的值的子表)
解决方案
在 PostgreSQL 的INSERT
语句中,您可以选择查询应返回的内容。来自INSERT 上的文档:
可选的 RETURNING 子句使 INSERT 根据实际插入的每一行(或更新的,如果使用了 ON CONFLICT DO UPDATE 子句)计算并返回值。这主要用于获取默认提供的值,例如序列号。但是,任何使用表列的表达式都是允许的。RETURNING 列表的语法与 SELECT 的输出列表的语法相同。只会返回成功插入或更新的行。
示例(您的查询的缩写形式):
WITH [...] INSERT INTO Tab1 ([...]) SELECT [...] FROM [...] RETURNING Tab1.id
推荐阅读
- sql - 循环遍历记录组
- c# - 为什么 .NET 在错误的 IF 语句上执行代码?
- fluent - 删除模块后 silverstripe 4 服务器错误
- javascript - 显示按钮激活
- drupal - 在 Drupal 8 管理员中添加一个弹出窗口
- javascript - 对 JSON 数据进行排序并获得前 n 条记录
- php - 将其用于 cron 作业的安全 Laravel URL
- pymodbus3 - pyModBus : 检查线圈是真还是假
- python-3.x - 如何在启动期间不使用 sudo 权限的情况下在 Scapy 解释器中启用语法提示和突出显示?
- lazy-loading - Zapier 延迟加载输入字段选择