如何将值从表A复制到表B,并在表B中插入对表B的引用?

时间:2018-09-05 09:55:09

标签: postgresql

我想将值从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列的方法来解决此问题?

1 个答案:

答案 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_insertsa_table.b_id的外键,则需要更新时加入b.id,以确保首先进行插入。