Question

First off, I'm using PSQL as my database engine. I have the following tables:

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'

And another table:

alerts
-------------------------------------------
feed_type_id | priority |   label   | feed_output_id
-------------------------------------------
     1            1       'Label1'       11

What I want to do is create an insert statement that selects all the feed outputs in the feed_outputs table where the feed_id=5 and use it in an insert statement that puts the feed_output_id into a new row in the alerts table.

I essentially want to combine the following two queries:

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>);

I've tried doing:

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));

But that obviously doesn't work with the select statement embedded into the values section of the insert statement. I'll want to keep the label the same (it's just an example field) and the only thing I want to vary is the feed output id. So my final alerts table should look like this:

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

Do you know of a query that can help me achieve this with the current table configuration?

Was it helpful?

Solution

I believe this is what you're looking for:

INSERT INTO alerts (feed_type_id,priority,label,feed_output_id)
SELECT 1,1,'Label2',id
  FROM feed_outputs
 WHERE feed_id = 5;

Try executing the SELECT once without the INSERT just to confirm that it's doing the right thing. Then you can tweak the query if needed.

This is called an INSERT INTO ... SELECT.

http://www.w3schools.com/sql/sql_insert_into_select.asp

OTHER TIPS

This should do it:

INSERT INTO alerts (feed_type_id,priority,label,feed_output_id) 
select 1,1,'Label2', id
from feed_outputs 
where feed_id=5;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top