首先,我使用 PSQL 作为我的数据库引擎。我有以下表格:
feed_outputs
----------------------------
id | feed_id | key ...
----------------------------
6 5 'Feed 1'
7 5 'Feed 2'
8 5 'Feed 3'
9 5 'Feed 4'
10 5 'Feed 5'
11 6 'Feed 1'
还有一张桌子:
alerts
-------------------------------------------
feed_type_id | priority | label | feed_output_id
-------------------------------------------
1 1 'Label1' 11
我想要做的是创建一个插入语句,该语句选择 feed_outputs 表中的所有提要输出,feed_id=5
并在插入语句中使用它,该语句将其feed_output_id
放入警报表的新行中。
我基本上想结合以下两个查询:
SELECT id FROM feed_outputs where feed_id=5;
INSERT INTO alerts (feed_type_id,priority,label,feed_output_id) VALUES
(1,1,'Label2', <each feed_output.id from statement above>);
我试过做:
WITH outputs AS (select * from feed_outputs where feed_id=5)
INSERT INTO alerts (feed_type_id,priority,label,feed_output_id) VALUES
(1,1,'Label2',(select outputs.id from outputs));
但这显然不适用于嵌入到 insert 语句的 values 部分的 select 语句。我希望标签保持不变(这只是一个示例字段),我唯一想要改变的是提要输出 ID。所以我的最终警报表应如下所示:
alerts
-------------------------------------------
feed_type_id | priority | label | feed_output_id
-------------------------------------------
1 1 'Label1' 11
1 1 'Label2' 6
1 1 'Label2' 7
1 1 'Label2' 8
1 1 'Label2' 9
1 1 'Label2' 10
您是否知道可以通过当前表配置帮助我实现此目的的查询?