【问题标题】:Insert multiple rows using the same foreign key that needs to be selected使用需要选择的相同外键插入多行
【发布时间】:2021-03-03 10:40:38
【问题描述】:

假设有两个表:

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

我想为同一产品插入多个 cmets。但我还不知道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';

【问题讨论】:

标签: sql postgresql join insert


【解决方案1】:

您的查询运行良好。它插入零行的唯一方法是,如果表products 中没有给定字符串的产品 - 在名为My product name 的查询中。但是,@a_horse_with_no_name 建议使用CROSS JOIN 可能会稍微简化您的查询。您可以将其与 CTE 结合以收集所有 cmets,然后将 CROSS JOIN 它与您从表格产品中过滤的记录结合起来。

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

【讨论】:

  • 你为什么在这里使用“临时”表?或者为什么这里有必要?对不起,如果这听起来很基本。我只是 SQL 的新手
  • @Priya 我只是使用临时表来保持我的系统清洁,因为一旦会话结束它们就会消失:-D 这个例子绝对没有必要
猜你喜欢
  • 1970-01-01
  • 2013-07-29
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
  • 2016-06-26
  • 2015-01-16
相关资源
最近更新 更多