PostgreSQL multi INSERT ... RETURN with multiple columns

I am creating a database with Postgres 9.3 as a backend, having 3 tables:

table1 (user_id, username, name, surname, emp_date)
table2 (pass_id, user_id, password)
table3 (user_dt_id, user_id, adress, city, phone)

As you can see, table2they table3are child tables table1.
I can extract the user_idrow just inserted into table1(parent):

INSERT INTO "table1" (default,'johnee','john','smith',default) RETURNING userid;

I need to insert the newly selected identifier (from table1) into the columns user_id table2and table3along with other data unique to these tables. Basically 3 X INSERT ...
How to do this?

+4
source share
1 answer

CTE, INSERT. - :

WITH ins1 AS (
   INSERT INTO table1 (username, name,  surname)
   VALUES ('johnee','john','smith')
   RETURNING user_id
   )
, ins2 AS (
   INSERT INTO table2 (user_id, password)
   SELECT ins1.user_id, 'secret'
   FROM   ins1                            -- nothing to return here
   )
INSERT INTO table3 (user_id, adress, city, phone)
SELECT ins1.user_id, ...
FROM   ins1
RETURNING user_id;
  • INSERT ( ad-hoc-). , , .

  • , DEFAULT. . , .

  • RETURNING , user_id (, - . user_id table3, , .

(a.k.a. "writeable" ) CTEs:

+4

Source: https://habr.com/ru/post/1534344/


All Articles