INSERT 多行与 RETURNING 子句中的 ID 组合

INSERT multiple rows combined with an ID from the RETURNING clause

这是我的查询:

WITH rows AS (INSERT INTO t_patch(f_name)VALUES('KB000')RETURNING f_patch_id)
INSERT INTO t_patch_available (f_patch_id, f_product_id)
SELECT f_patch_id,7 FROM rows;

有效。但是,如果我想插入几个具有相同 f_patch_idt_patch_available,语法是什么?

您可以在 select 上使用联合来添加更多行。

WITH rows AS (INSERT INTO t_patch(f_name)VALUES('KB001')RETURNING f_patch_id)
INSERT INTO t_patch_available (f_patch_id, f_product_id) 
SELECT f_patch_id,7 FROM rows 
UNION ALL SELECT f_patch_id, 8 FROM rows

您不想每行使用一个 SELECT,这对于多行来说不必要地冗长且昂贵。 CROSS JOIN 到一组 ID(假设 product_id 是 integer)。

WITH rows AS (INSERT INTO t_patch(f_name) VALUES ('KB000') RETURNING f_patch_id)
INSERT INTO t_patch_available (f_patch_id, f_product_id)
SELECT f_patch_id, product_id
FROM   rows
     , unnest ('{6,8,9,11,345}'::int[]) product_id;  -- set of product_id's

或者您可以使用 VALUES 表达式:

...
FROM   rows
    , (VALUES (6) ,(8), (9), (11), (345)) AS p(product_id);  -- set of product_id