将插入的id插入另一个表

时间:2014-12-21 10:31:30

标签: sql postgresql triggers primary-key entity-relationship

以下是该方案:

create 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表时a引用a创建记录。但我得到的是new.id为空,因为它是从序列自动生成的。我还尝试了触发器AFTER插入FOR EACH ROW,但结果是一样的。有办法解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

避免使用规则,因为他们会回来咬你。

对每行运行的表a使用after触发器。它应该看起来像这样(未经测试):

create 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 a
for each row execute procedure a_ins();

答案 1 :(得分:2)

为了简单起见,您还可以使用data-modifying CTE(并且没有触发器或规则):

WITH ins_a AS (
   INSERT INTO a(val)
   VALUES ('foo')
   RETURNING a_id
   )
INSERT INTO b(a_id)
SELECT a_id
FROM   ins_a
RETURNING b.*;  -- last line optional if you need the values in return

相关答案以及更多细节:

或者您可以使用currval() and lastval()

答案 2 :(得分:-1)

不要使用触发器或其他数据库功夫。这种情况发生在世界的某个地方 - 有一个简单的解决方案:

插入后,使用LASTVAL()函数,该函数返回自动递增的最后一个序列的值。

您的代码如下:

insert into a (val) values ('foo');
insert into b (a_id, val) values (lastval(), 'bar');

易于阅读,维护和理解。

相关问题