2014-04-01 42 views
0

我想插入到一個CTE的主表後插入我的外鍵在多個表中。我無法找到解決方案,因此它很可能是不可能的...是否可以在Postgres的CTE語句中多次使用返回值?

看看這個例子:

CREATE TABLE test_main (main_id serial NOT NULL, main_name character varying(64) default null); 
CREATE TABLE test_sub_one (sub_one_id serial NOT NULL,sub_one_main_id integer NOT NULL,sub_one_name character varying(64) default null); 
CREATE TABLE test_sub_two (sub_two_id serial NOT NULL,sub_two_main_id integer NOT NULL,sub_two_name character varying(64) default null); 

WITH main as (
    INSERT INTO test_main (main_name) VALUES ('test1') RETURNING main_id 
) 
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; 

回答

1

使用另一種CTE第二插入:

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

非常感謝您! – DeniseMeander

相關問題