INSERT in single query into 2 tables postgresql

后端 未结 1 575
悲哀的现实
悲哀的现实 2021-02-15 04:22

I have this 3 tables.

Employee
PK : id
name

completedBy
FK : employee_id
FK : order_id

Order
PK : id
date

I created form for creating order w

1条回答
  •  梦谈多话
    2021-02-15 05:06

    This can be done using a data modifying common table expression:

    with new_order as (
      insert into orders (id, date) values (1, current_date)
      returning id
    )
    insert into completedby (employee_id, order_id)
    values 
    ( 42 -- employee_id, 
      (select id from new_order)
    );
    

    The first part inserts into the orders table and returns the ID that was inserted. The second part then inserts the row into the completedby table using the known employee_id and retrieving the order_id from the previous step.

    Edit

    if the id column in the orders table is a serial column and you want to let the sequence generate the value you can do that as well:

    with new_order as (
      insert into orders (date) values (current_date)
      returning id
    )
    insert into completedby (employee_id, order_id)
    values 
    ( 42 -- employee_id, 
      (select id from new_order)
    );
    

    0 讨论(0)
提交回复
热议问题