Need magic for inserting in 2 tables - Mailing list pgsql-sql

From Andreas
Subject Need magic for inserting in 2 tables
Date
Msg-id 4CA9004E.7060106@gmx.net
Whole thread Raw
Responses Re: Need magic for inserting in 2 tables  (Scott Marlowe <scott.marlowe@gmail.com>)
List pgsql-sql
  Hi,

I need to insert a lot of basically blank records into a table to be 
filled later.
Sounds silly but please bear with me.  :)

projects ( project_id, project_name, ... )
companies ( company_id, ... )
departments ( department_id, department )
staff ( staff_id  SERIAL,  company_fk, department_fk, ...   )

company_2_project ( project_fk, company_fk )
staff_2_project ( project_fk, staff_fk, project data, ... )

So with this I can store that company 99 belongs e.g. to project 3, 5 and 42
and staff_id 11, 13, 17 belongs to company 99.

staff_2_project represents the connection of staff members to a project 
and holds projectrelated infos.

Now say I have allready 100 companies out of the bigger adress pool 
connected to project 42 and I now want to add blank  staffers out of 
department  40 and 50  linked with this project.

I do step 1:

insert into staff ( company_fk, ..., department_fk )
select  company_fk, ..., department_fk
from     departments,   companies,   company_2_project  AS c2p
where  company_id      =   c2p.company_fk    and c2p.project_fk    =   42    and department_id  in  ( 40, 50 );

step 2 would be to link those new blank staff records to project 42 by 
inserting a record into staff_2_project for every new staff_id.

How can I find the new staff_ids while making sure I don't insert ids 
from other sessions?
Is there an elegant way in SQL ?


pgsql-sql by date:

Previous
From: Frank Bax
Date:
Subject: join returns too many results...
Next
From: Scott Marlowe
Date:
Subject: Re: Need magic for inserting in 2 tables