How do I insert multiple rows with a foreign key using a CTE in Postgres?

后端 未结 2 904
一向
一向 2021-01-03 10:08

I want to do a bulk insert transaction but I\'m not too sure how to do this using CTEs or a more efficient method. This is what I have so far:

with bulky as         


        
2条回答
  •  青春惊慌失措
    2021-01-03 10:34

    The following is a reasonable interpretation of what you want to do:

    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;
    

    The basic answer is "use returning * and use a join to get the values". I needed to change the titles so they are unique.

提交回复
热议问题