我可以在另一个INSERT中使用INSERT ... RETURNING的返回值吗? [英] Can I use return value of INSERT...RETURNING in another INSERT?

查看:436
本文介绍了我可以在另一个INSERT中使用INSERT ... RETURNING的返回值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样可能吗?

INSERT INTO Table2 (val)
VALUES ((INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id));

喜欢使用返回值作为值在第二个表中插入对第一个表的引用的行吗?

like using the return value as value to insert a row in a second table with a reference to the first table?

推荐答案

您可以从Postgres 9.1开始:

You can do so starting with Postgres 9.1:

with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val)
SELECT id
FROM rows

与此同时,如果您仅对ID感兴趣,则可以使用触发器进行操作:

In the meanwhile, if you're only interested in the id, you can do so with a trigger:

create function t1_ins_into_t2()
  returns trigger
as $$
begin
  insert into table2 (val) values (new.id);
  return new;
end;
$$ language plpgsql;

create trigger t1_ins_into_t2
  after insert on table1
for each row
execute procedure t1_ins_into_t2();

这篇关于我可以在另一个INSERT中使用INSERT ... RETURNING的返回值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆