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

前端 未结 2 783
长情又很酷
长情又很酷 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

    0 讨论(0)
  • 2021-01-28 15:56

    DEFAULT will work for SERIAL as it sets default value for column. So

    INSERT INTO Purchase VALUES (DEFAULT,'Lendl');
    

    should work. But PurchasedItem.purchaseID has no default value set, so it it tries to insert NULL (and null is not in referenced column yet), so it fails.

    try:

    INSERT INTO Purchase(custName) VALUES ('Lendl') RETURNING purchaseID;
    

    you will see the value of inserted purchaseID, use it in next query:

    INSERT INTO PurchasedItem(purchaseID, itemNo) VALUES (_the_value_above_, 111);
    commit;
    

    If you want it to be used without interactivity, use DO block with returning purchaseID into _value

    update:

    or cte, smth like

    WITH i AS (
      INSERT INTO Purchase(custName, orderedDate) 
      VALUES ('Lendl', '2016-09-28') 
      RETURNING purchaseID
    )
    insert into PurchasedItem
    select i.purchaseID,'smth',3
    from i
    
    0 讨论(0)
提交回复
热议问题