我有 3 张桌子:
CREATE TABLE stage
(
a1 text,
b2 text,
c3 text,
d4 text,
e5 text
);
CREATE TABLE main
(
id bigserial PRIMARY KEY,
a1 text,
b2 text,
c3 text
);
CREATE TABLE secondary (
id bigserial PRIMARY KEY,
mainid bigint,
d4 text,
e5 text,
CONSTRAINT secondary_fkey FOREIGN KEY(mainid) REFERENCES main(id)
);
我想一次插入数据,stage
但main
我secondary
不太确定如何通过重用生成的 bigserial in 来做到这一点main
。我正在尝试,with query
但我得到的行数(指数)secondary
比预期的要多。
WITH tmp AS (
INSERT INTO
main (a1, b2, c3)
SELECT
a1,
b2,
c3
FROM
stage RETURNING id
)
INSERT INTO
secondary (mainid, d4, e5)
SELECT
tmp.id,
stage.d4,
stage.e5
FROM
tmp,
stage;