【发布时间】: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';
【问题讨论】:
-
为我工作:dbfiddle.uk/… 你的具体问题是什么?
-
我会使用交叉连接:dbfiddle.uk/…
标签: sql postgresql join insert