How to determine the auto-generated primary key used as a foreign key for another table

前端 未结 1 871
醉梦人生
醉梦人生 2020-12-22 05:34

This is a two-part question. Attached is a diagram for a PostgreSQL database table design. There are four tables. Table Main has a one-to-many relationship wi

相关标签:
1条回答
  • 2020-12-22 06:07

    Answer to Q1: Use data-modifying CTEs and return the serial PK with the RETURNING clause:

    WITH ins_main AS (
       INSERT INTO main(col1)
       VALUES ('some value 1')
       RETURNING main_id    
       )
    , ins_submain AS (
       INSERT INTO submain (main_id, col2)
       SELECT main_id, 'some value 2'
       FROM   ins_main
       RETURNING submain_id
       )
    INSERT INTO subsub (submain_id, col3)
    SELECT submain_id, 'some value 3'
    FROM   ins_submain;
    

    Requires Postgres 9.1 or later.
    Related answers with explanation and links:

    • Insert data in 3 tables at a time using Postgres
    • PostgreSQL store value returned by RETURNING
    0 讨论(0)
提交回复
热议问题