Is it possible to have multiple secondary use of a returning value in a CTE statement in Postgres?

前端 未结 1 341
灰色年华
灰色年华 2021-01-26 09:17

I want to insert my foreign keys in multiple tables after a insert into the main table in one CTE. I can\'t find the solution so it may well be impossible...

see this ex

相关标签:
1条回答
  • 2021-01-26 09:32

    Use another CTE for the second insert:

    WITH main as (
        INSERT INTO test_main (main_name) VALUES ('test1') RETURNING main_id
    ), sub1 as (
      INSERT INTO test_sub_one (sub_one_main_id,sub_one_name) 
      SELECT main_id, 'testsub1' FROM main
    )
    INSERT INTO test_sub_two (sub_two_main_id,sub_two_name) 
    SELECT main_id, 'testsub2' FROM main;
    
    0 讨论(0)
提交回复
热议问题