简体   繁体   English

在单个查询中INSERT到2个表postgresql中

[英]INSERT in single query into 2 tables postgresql

I have this 3 tables. 我有这3张桌子。

Employee
PK : id
name

completedBy
FK : employee_id
FK : order_id

Order
PK : id
date

I created form for creating order where i fill infos of order (date) and who completed order. 我创建了用于创建订单的表单,其中我填写订单的信息(日期)和完成订单的人。 In my form there is a table from which I select the employee and get his id. 在我的表格中有一张桌子,我从中选择员工并获得他的身份证。 I want to know if there is possible to insert into tables Order and completedBy with one single query. 我想知道是否有可能使用单个查询插入表Order和completedBy。

Is there any difference in effectivity between using two inserts or using the code in answer ? 使用两个插入或使用答案中的代码之间的有效性是否有任何差异?

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. 第一部分插入到orders表中并返回插入的ID。 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. 然后,第二部分使用已知的employee_id将行插入到completedby表中,并从上一步中检索order_id。

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: 如果orders表中的id列是一个serial列,并且您希望让序列生成值,那么您也可以这样做:

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)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM