Return 来自 postgresql 插入的 id

Return id from postgresql insertion

在外部应用程序中,我想执行以下操作:

  1. 插入条目到 table A
  2. 向tableB中插入一堆条目,以我在A中新插入的条目的id作为外键

所以 table 看起来像这样:

A(_id, data)

B(_id, other_data)
     _id --> A._id

仅在 postgresql 中可以实现吗?或者是否可以在 table A 中的项目创建后将 id return 添加到我的应用程序,以便我的应用程序可以添加其余值?

我看过 following post,但它的语法不正确,导致无限循环,导致堆栈溢出(多么讽刺)。

有几种方法可以做到:

假设 a._idserial 列:

insert into a (data) values ('foo');
insert into b (_id, other_data) values (lastval(), 'foobar');

编辑(在评论中讨论后): 请注意 lastval() 是并发安全的(因为 all 序列相关函数)。即使其他会话在两个语句之间的 a 中插入了一些内容,lastval() 仍然会 return 与 current 会话相关的值(即那个由之前的 insert)

生成

您已经链接到的问题中详细描述了其他方法:

或使用数据修改 CTE:

with insert_a as (
    insert into a (data) values ('foo')
    returning _id
)
insert into b (_id, other_data)
values 
  ((select _id from insert_a), 'one'), 
  ((select _id from insert_a), 'two'), 
  ((select _id from insert_a), 'three');