INSERT rows into multiple tables in a single query, selecting from an involved table

前端 未结 2 2190
悲&欢浪女
悲&欢浪女 2020-11-27 16:29

I have two tables of the following form (i.e., every foo is linked to exactly one bar).

CREATE TABLE foo (
    id INTEGER PRIMARY KEY,
    x INTEGER NOT NULL         


        
2条回答
  •  一整个雨季
    2020-11-27 17:34

    if id of bar is serial and have default value nextval('bar_id_seq'::regclass) you can manually call this function to get new ids in cte

    with
    s_bar as (
      SELECT id, z, nextval('bar_id_seq'::regclass) new_id
      FROM   bar
      WHERE  ...
    ),
    s_foo as (
      SELECT x, y, bar_id
      FROM   foo
      WHERE  ...
    ),
    i_bar as (
      INSERT INTO bar (id, z)
      SELECT new_id, z
      FROM   s_bar
    ),
    i_foo as (
      INSERT INTO foo (x, y, bar_id)
      SELECT f.x, f.y, b.new_id
      FROM   s_foo f
      JOIN   s_bar b on b.id = f.bar_id
    )
    SELECT 1
    

提交回复
热议问题