在Postgres中引用多个插入事务中的插入ID

时间:2019-05-31 09:43:44

标签: sql postgresql transactions foreign-keys relational-database

我需要构建一个SQL查询,该查询必须能够在第一个表中插入数据,获取插入的ID,然后将其用作下表中的外键。

WITH inserted AS (
    INSERT INTO firstTable (name) VALUES ('somename') RETURNING id
)

SELECT * FROM inserted; -- this has the inserted id

INSERT INTO secondTable (name, foreign_id) VALUES ('someexternalname', ???)

那么如何在id插入中引用inserted中的secondTable

3 个答案:

答案 0 :(得分:2)

您可以这样做:

WITH inserted AS (
    INSERT INTO firstTable (name) VALUES ('somename') RETURNING id
)

INSERT INTO secondTable (name, foreign_id)
SELECT
'someexternalname',
id
FROM inserted;

答案 1 :(得分:2)

您已经完成了80%,完整的SQL是:

with inserted as (
 insert into first_table(name) values ('somename') returning id
)
insert into second_table(name, foreign_id) select 'someexternalname',id from inserted

答案 2 :(得分:0)

您可以尝试以下方法:

INSERT INTO secondTable (name, foreign_id) VALUES ('someexternalname', (SELECT 
MAX (id) FROM firstTable))