回答

收藏

将插入的ID插入另一个表

技术问答 技术问答 165 人阅读 | 0 人回复 | 2023-09-13

这是场景:
) ^9 D9 b# w, kcreate table a ( id serial primary key,val text);create table b ( id serial primary key,a_id integer references a(id));create rule a_inserted as on insert to a do also insert into b (a_id) values (new.id);我试图在插入表时创建它b引用记录。但我得到的是null,因为它是从序列中自动生成的。我也试着插入触发器,但结果是一样的。有什么解决办法吗?a``a``new.id``AFTER``FOREACH ROW: Q. q/ Q; n9 {9 ^4 W
                                                               
: z$ L+ v  ^; y6 K    解决方案:                                                                $ u# b2 \, g$ P! i+ D9 v" a0 j
                                                                避免使用规则,因为它们会再次咬你。
+ m( z2 r' [8 K  Q4 U8 g5 U每次操作的表a上使用after触发器。它应该看起来像这样(未经测试):
, m1 f4 U5 {1 |" b5 q1 ccreate function a_ins() returns trigger as $$begin  insert into b (a_id) values (new.id);  return null;end;$$ language plpgsql;create trigger a_ins after insert on afor each row execute procedure a_ins();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则