I need insert 2 records in differents tables,

2019-08-22 14:29发布

I need to insert 2 records into 2 different tables. The problem is that the two records will be with the same Id. For example :

I have my Mannto table, with its IdMan and oters fields. I also have my Service table, with its IdServ.

What can I do to make this one equal? I am using Postgre. The Id of the Mannto table is serial and I need to use that one as a Foreign key in the Service table

I tried the following, but it does not work:

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')

Thank you for any help you can provide!

3条回答
做自己的国王
2楼-- · 2019-08-22 14:35
INSERT INTO Mannto ( field1, field2 ...etc) VALUES ( 'f1', 'f2'...etc)
  RETURNING idMan;

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

查看更多
对你真心纯属浪费
3楼-- · 2019-08-22 14:44

When field idMan uses a sequence to create a new value, you can refer to this value in the next INSERT using CURRVAL():

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
查看更多
老娘就宠你
4楼-- · 2019-08-22 14:55

Maybe it's not the best solution but you could use a trigger.

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

Fetch your MannTo inserted last code and throw the procedure after each insert.

查看更多
登录 后发表回答