您可以根據需要將您的格式擴展到多個表格。這裏是一個主表和兩個相關表格,並取回最終結果的幾種方法的例子:
這些都是使用的表:
CREATE TABLE main
(
main_id serial PRIMARY KEY,
main_text text
) ;
CREATE TABLE age
(
main_id integer REFERENCES main(main_id) PRIMARY KEY,
birthdate date NOT NULL,
CHECK(birthdate <= now())
) ;
CREATE TABLE preferred_colours
(
main_id integer NOT NULL REFERENCES main(main_id),
colour text NOT NULL,
PRIMARY KEY(main_id, colour)
) ;
這是一個CTE,你在三個表中插入,並取得了一些成果:
WITH insert_main AS
(
INSERT INTO main (main_text)
VALUES ('Main text')
RETURNING main_text, main_id
)
, insert_age AS
(
INSERT INTO age (main_id, birthdate)
VALUES ((SELECT main_id FROM insert_main), '2017-01-01')
RETURNING main_id, birthdate
)
, insert_colours AS
(
INSERT INTO preferred_colours (main_id, colour)
SELECT
main_id, colour
FROM
insert_main
CROSS JOIN
(SELECT 'blue' AS colour
UNION
SELECT 'red'
UNION
SELECT 'green'
) AS colours
RETURNING
*
)
SELECT
insert_main.main_id
,insert_main.main_text
,insert_age.birthdate
,(SELECT string_agg(colour, ', ' ORDER BY colour)
FROM insert_colours
) AS preferred_colours_list
FROM
insert_main
CROSS JOIN insert_age
main_id | main_text | birthdate | preferred_colours_list
------: | :-------- | :--------- | :---------------------
1 | Main text | 2017-01-01 | blue, green, red
dbfiddle here
你可以使用觸發器來做到這一點 –
一個觸發器不是一個單一的聲明! – user3791372
您可以使用多個CTE。 –