I have three tables:
table1(id, name, foo)
table2(id, name)
table3(id, id2, name, foo, bar)
And I'd like to copy data from table1 to tables 2 & 3, but table3.id2 has to correspond to the row in table2. I think I need to do something with the RETURNING command, but I have been unsuccessful.
WITH oldstuff AS (
SELECT name, foo, 'some value' AS bar
FROM table1
),
newstuff AS (
INSERT INTO table2 (name)
SELECT name FROM oldstuff
RETURNING id AS id2 /* but i also need oldstuff.name, oldstuff.foo,and oldstuff.bar */
)
INSERT INTO table3 (id2, name, foo, bar)
SELECT * FROM newstuff; /* I cant just do a join here because the fields arent unique */