使用需要选择的相同外键插入多行

Insert multiple rows using the same foreign key that needs to be selected

假设有两个表:

CREATE TABLE products (id SERIAL, name TEXT);
CREATE TABLE comments (id SERIAL, product_id INT, txt TEXT);

我想为同一产品插入多条评论。但是我还不知道product_id,只知道产品名称。

所以我可以这样做:

INSERT INTO comments (txt, product_id) VALUES
    ( 'cool', (SELECT id from products WHERE name='My product name') ),
    ( 'great', (SELECT id from products WHERE name='My product name') ),
    ...
    ( 'many comments later', (SELECT id from products WHERE name='My product name') );

我想减少重复。如何做到这一点?

我试过了,但它没有插入任何行:

INSERT INTO
  comments (txt, product_id)
SELECT
  x.txt,
  p.id
FROM
  (
    VALUES
      ('Great product'),
      ('I love it'),
      ...
      ('another comment')
  ) x (txt)
  JOIN products p ON p.name = 'My product name';

您的查询工作正常。它插入零行的唯一方法是如果给定字符串的 table products 中没有产品 - 在名为 My product name 的查询中。然而,@a_horse_with_no_name 的建议是使用 CROSS JOIN might simplify your query a bit. You can combine it with a CTE 收集所有评论,然后 CROSS JOIN 它与您从 table 产品中过滤的记录。

CREATE TABLE products (id SERIAL, name TEXT);
CREATE TABLE comments (id SERIAL, product_id INT, txt TEXT);    
INSERT INTO products VALUES (1, 'My product name'),(2,'Another product name');

WITH j (txt) AS (
  VALUES ('Great product'),('I love it'),('another comment')
) 
INSERT INTO comments (product_id,txt)
SELECT id,j.txt FROM products
CROSS JOIN j WHERE name = 'My product name';

SELECT * FROM comments;  
 id | product_id |       txt       
----+------------+-----------------
  1 |          1 | Great product
  2 |          1 | I love it
  3 |          1 | another comment

勾选这个db<>fiddle