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

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

提交回复
热议问题