How do I insert a record and put the ID into an existing record in another table?
2
votes
1
answer
498
views
I want to insert a record in one table and save the resuting ID in a record I already have in another table. Which sounds easy.
Simplistic example:
create table aaa (id serial primary key, foo int);
create table foos (id serial primary key, foo int, aaa_id int);
Imagine foos has rows which I want to insert in aaa. But I want a record of
aaa.id
stored in foos.aaa_id
.
Heres some code that definitely does not work:
with rows as (
insert into aaa (foo)
select foo from foos
returning foos.id as foos_id, aaa.id as aaa_id
)
update foos
set aaa_id = (select aaa_id from rows where foos_id = foos.id);
I can't find a way of getting the "returning" clause to return anything other than records from the table it inserted.
Surely there must be a simple way to do this?
Asked by Andy Jones
(123 rep)
Jul 8, 2016, 11:18 AM
Last activity: Dec 21, 2024, 07:37 AM
Last activity: Dec 21, 2024, 07:37 AM