How to get child table's foreign key to have same value as parent's primary auto-increment key

前端 未结 2 796
长情又很酷
长情又很酷 2021-01-28 15:11

I have created these two tables:

CREATE TABLE Purchase(
purchaseID SERIAL,
custName VARCHAR(30) NOT null,
PRIMARY KEY (purchaseID));

CREATE TABLE PurchasedItem(         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-28 15:54

    You can use lastval()

    INSERT INTO Purchase(custName) VALUES ('Lendl');
    INSERT INTO PurchasedItem(purchaseID, itemNo) VALUES (lastval(), 111);
    commit;
    

    Alternatively query the underlying sequence directly:

    INSERT INTO Purchase(custName) VALUES ('Lendl');
    INSERT INTO PurchasedItem(purchaseID, itemNo) 
    VALUES (currval('purchase_purchaseid_seq'), 111);
    commit;
    

    Or if you don't want to rely on the automatic naming of the sequence, use pg_get_serial_sequence to get the sequence associated with the column:

    INSERT INTO Purchase(custName) VALUES ('Lendl');
    INSERT INTO PurchasedItem(purchaseID, itemNo) 
    VALUES (currval(pg_get_serial_sequence('purchase', 'purchaseid')), 111);
    commit;
    

    For more details see the manual: https://www.postgresql.org/docs/current/static/functions-sequence.html

提交回复
热议问题