我需要在不同的表中插入2条记录,

时间:2011-08-10 16:27:23

标签: sql postgresql insert

我需要在2个不同的表中插入2条记录。问题是这两个记录将具有相同的Id。 例如:

我有我的Mannto表,其IdMan和oters字段。我还有我的服务表及其IdServ。

我能做些什么来使这个平等?我正在使用Postgre。 Mannto表的Id是串行的,我需要在Service表中使用那个作为外键

我尝试了以下操作,但它不起作用:

Insert into Mannto ( idMan, field 1 field2 ...etc) 
            values ( default, 'f1', 'f2'...etc)

Insert into Service ( idServ, fkMannto, field1...etc) 
             values (default, (in this part I need the same ManntoId called idMan), 'f1')

感谢您提供任何帮助!

3 个答案:

答案 0 :(得分:2)

INSERT INTO Mannto ( field1, field2 ...etc) VALUES ( 'f1', 'f2'...etc)
  RETURNING idMan;

http://www.postgresql.org/docs/current/static/sql-insert.html

答案 1 :(得分:1)

当字段idMan使用序列创建新值时,您可以使用CURRVAL()在下一个INSERT中引用此值:

BEGIN; -- start transaction
      INSERT INTO Mannto ( idMan, field 1 field2 ...etc) 
        VALUES ( default, 'f1', 'f2'...etc);   
      INSERT INTO Service ( idServ, fkMannto, field1...etc) 
        VALUES (default, currval('name_of_the_sequence') , 'f1');
COMMIT; -- commit both inserts

答案 2 :(得分:0)

也许这不是最佳解决方案,但您可以使用触发器。

CREATE TRIGGER MannToTrigger
AFTER INSERT OR UPDATE OR DELETE ON MannTo
    FOR EACH ROW EXECUTE PROCEDURE insertService();

获取MannTo插入的最后一个代码,并在每次插入后抛出该过程。

相关问题