我想将值从a_table.foo
复制到b_table.bar
并将生成的b_table.id
插入a_table.b_id
:
WITH b_inserts AS (
INSERT INTO b_table (bar)
SELECT foo
FROM a_table
RETURNING id as b_id, a_table.id as a_id
)
UPDATE a_table
SET b_id = b_inserts.b_id
FROM b_inserts
WHERE a.id = b_inserts.a_id
http://sqlfiddle.com/#!17/13819/1
它失败了,因为我无法从a_table.id
返回b_inserts
,因为它不是插入行的一部分,RETURNING
可以访问所有行。
是否有一种无需创建临时b_table.a_id
列的方法来解决此问题?
答案 0 :(得分:2)
您可以在插入之前生成映射:
WITH a_to_b_mapping AS (
SELECT nextval('b_table_id_seq'::regclass) b_id, foo, id AS a_id
FROM a_table
), b_inserts AS (
INSERT INTO b_table (id, bar)
SELECT b_id, foo
FROM a_to_b_mapping
RETURNING id
)
UPDATE a_table a
SET b_id = m.b_id
FROM a_to_b_mapping m
JOIN b_inserts i ON i.id = m.b_id
WHERE a.id = m.a_id
请注意,如果您有从b_inserts
到a_table.b_id
的外键,则需要更新时加入b.id
,以确保首先进行插入。