首页 > 解决方案 > 在 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

解决方案


在 PostgreSQL 的INSERT语句中,您可以选择查询应返回的内容。来自INSERT 上的文档

可选的 RETURNING 子句使 INSERT 根据实际插入的每一行(或更新的,如果使用了 ON CONFLICT DO UPDATE 子句)计算并返回值。这主要用于获取默认提供的值,例如序列号。但是,任何使用表列的表达式都是允许的。RETURNING 列表的语法与 SELECT 的输出列表的语法相同。只会返回成功插入或更新的行。

示例(您的查询的缩写形式):

WITH [...] INSERT INTO Tab1 ([...]) SELECT [...] FROM [...] RETURNING Tab1.id

推荐阅读