我想用一个查询将数据插入3个表中。我的表格如下所示:CREATE TABLE sample ( id bigserial PRIMARY KEY, lastname varchar(20), firstname varchar(20));CREATE TABLE sample1( user_id bigserial PRIMARY KEY, sample_id bigint REFERENCES sample, adddetails varchar(20));CREATE TABLE sample2( id bigserial PRIMARY KEY, user_id bigint REFERENCES sample1, value varchar(10));每次插入我都会得到一个密钥作为回报,我需要将该密钥插入下表。我的查询是:insert into sample(firstname,lastname) values('fai55','shaggk') RETURNING id;insert into sample1(sample_id, adddetails) values($id,'ss') RETURNING user_id;insert into sample2(user_id, value) values($id,'ss') RETURNING id;但是,如果我运行单个查询,它们只会向我返回值,而我不能立即在下一个查询中重用它们。如何实现呢?
3 回答
皈依舞
TA贡献1851条经验 获得超3个赞
像这样
with first_insert as (
insert into sample(firstname,lastname)
values('fai55','shaggk')
RETURNING id
),
second_insert as (
insert into sample1( id ,adddetails)
values
( (select id from first_insert), 'ss')
RETURNING user_id
)
insert into sample2 ( id ,adddetails)
values
( (select user_id from first_insert), 'ss');
由于sample2不需要从insert into生成的ID ,因此我returning从最后一个insert中删除了该子句。
- 3 回答
- 0 关注
- 773 浏览
添加回答
举报
0/150
提交
取消