这是我的问题:
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;
有效。但是,如果我想要使用相同的t_patch_available
插入多个f_patch_id
?
答案 0 :(得分:0)
您可以在select上使用union来添加更多行。
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
答案 1 :(得分:0)
您不希望每行使用一个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