agora inbox for pgsql-sql@postgresql.org
help / color / mirror / Atom feedFrom: Michael Schmidt <css.liquid@gmail.com>
To: Jonathan S. Katz <jonathan.katz@excoventures.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: How to script inserts where id is needed as fk
Date: Sat, 09 Nov 2013 21:09:50 +0100
Message-ID: <527E968E.8010807@gmail.com> (raw)
In-Reply-To: <05069440-C45F-4763-81A8-E14B5CB1CCB5@excoventures.com>
References: <527D3F2A.6060504@gmail.com>
<05069440-C45F-4763-81A8-E14B5CB1CCB5@excoventures.com>
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-sql>
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?
--
Sent via pgsql-sql mailing list (pgsql-sql@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-sql
view thread (6+ messages) latest in thread
Message-ID: <527E968E.8010807@gmail.com>
Permalink: ../527E968E.8010807@gmail.com/
Also on: postgresql.org/message-id/527E968E.8010807@gmail.com
reply
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: css.liquid@gmail.com, jonathan.katz@excoventures.com
Subject: Re: How to script inserts where id is needed as fk
In-Reply-To: <527E968E.8010807@gmail.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox