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

亡梦爱人 提交于 2019-11-29 18:07:21
Erwin Brandstetter

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!