Re: How to script inserts where id is needed as fk

From: "Jonathan S(dot) Katz" <jonathan(dot)katz(at)excoventures(dot)com>
To: Michael Schmidt <css(dot)liquid(at)gmail(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: How to script inserts where id is needed as fk
Date: 2013-11-09 21:15:38
Message-ID: 8184E4E2-3585-42E2-B7CA-FFE549965C9E@excoventures.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Nov 9, 2013, at 3:09 PM, Michael Schmidt wrote:

> Am 08.11.2013 20:48, schrieb Jonathan S. Katz:
>> On Nov 8, 2013, at 2:44 PM, Michael Schmidt wrote:
>>
>>> Hi guys,
>>>
>>> i need to script some insert statements. To simplify it a little bit so assume i got a
>>>
>>> table "User" and a table called "Article". Both tables have an serial id column. In "Articles" there is a column i need to fill with the user id lets call it "create_user_id".
>>>
>>> I want to do something like:
>>>
>>> Insert into User (name) values ('User1');
>>>
>>> Insert into Article ('create_user_id') values (1);
>>> Insert into Article ('create_user_id') values (1);
>>>
>>> Insert into User (name) values ('User2');
>>>
>>> Insert into Article ('create_user_id') values (2);
>>> Insert into Article ('create_user_id') values (2);
>>>
>>> So you see i have set it to 1 and 2 this not good cause it might not be 1 and 2.
>>> I probably need the id returned by the "insert into User" query to use it for the "insert into Article" query.
>> If you are on PG 9.1 and above, you can use a writeable CTE to do this:
>>
>> WITH users AS (
>> INSERT INTO User (name)
>> VALUES ('user1')
>> RETURNING id
>> )
>> INSERT INTO Article ('create_user_id')
>> SELECT id
>> FROM users;
>>
>> Jonathan
>>
> Thanks.
>
> This will work if i am trying to insert just one article but i have multiple.
>
> To extend my scenario a little bit i have a third level called 'Incredient' and they need the Article id. I dont think this will work anymore with the with clause. Any new approaches?

You can chain CTEs, see pseudocode below:

WITH a AS (
-- INSERT code
), b AS (
-- INSERT code
-- SELECT *
-- FROM a
)
INSERT INTO c
SELECT *
FROM b

Jonathan

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message David Johnston 2013-11-09 21:55:16 Re: How to script inserts where id is needed as fk
Previous Message Michael Schmidt 2013-11-09 20:09:50 Re: How to script inserts where id is needed as fk