我需要构建一个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
?
答案 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))