我想将值从 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
它失败了,因为我无法从 b_inserts
返回 a_table.id
,因为它不是插入行的一部分,RETURNING
可以访问。
有没有办法在不必创建临时 b_table.a_id
列的情况下解决这个问题?
最佳答案
您可以在执行插入之前生成映射:
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
.
关于postgresql - 如何将表 A 中的值复制到 B 并在 A 中插入对 B 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52182241/