如何在 Postgres 中使用 CTE 插入带有外键的多行?

Jam*_*aal 4 sql postgresql

我想做一个批量插入事务,但我不太确定如何使用 CTE 或更有效的方法来做到这一点。这是我到目前为止:

with bulky as (
    insert into products (title, description, price) 
                  values ('Dope product 1', 'Buy diz', 9.99), 
                         ('Dope product 2', 'Buy diz', 8.99), 
                         ('Dope product 2', 'Buy diz', 7.99) 
                  returning id
) 
insert into product_metadata (product_id, sales_volume, date) 
                       values (???, 80, '2017-03-21'), 
                              (???, 50, '2017-03-21'), 
                              (???, 70, '2017-03-21');
Run Code Online (Sandbox Code Playgroud)

我的 CTE 的问题是我不知道如何从第一个插入语句中获取单个 id,以插入到具有“product_id”外键的第二个语句的相应记录中。

我将如何构建语句以使其工作?我对替代解决方案持开放态度,这些解决方案提供了一种更有效的方法来实现相同的结果。

Gor*_*off 5

以下是对您要执行的操作的合理解释:

with i as (
      insert into products (title, description, price)
          values ('Dope product 1', 'Buy diz', 9.99),
                 ('Dope product 2', 'Buy diz', 8.99),
                 ('Dope product 3', 'Buy diz', 7.99)
          returning *
     ) 
insert into product_metadata (product_id, sales_volume, date)
    select i.product_id, v.sales_volume, v.date
    from (values ('Dope product 1', 80, '2017-03-21'),
                 ('Dope product 2', 50, '2017-03-21'), 
                 ('Dope product 3', 70, '2017-03-21')
         ) v(title, sales_volume, date) join
         i
         on i.title = v.title;
Run Code Online (Sandbox Code Playgroud)

基本答案是“使用returning *并使用 ajoin来获取值”。我需要更改标题,使它们独一无二。