What Causes The INSERT statement conflicted with the FOREIGN KEY constraint?

前端 未结 2 1375
梦如初夏
梦如初夏 2020-12-16 01:09

This code has worked for me before but i am not sure anymore what has been causing this error. My only guess is that when i try to create a Player, the Team Data is being se

2条回答
  •  臣服心动
    2020-12-16 01:26

    The reason behind this is when you are inserting a record on the child table which the value of the referencing column doesn't exist yet on the on the parent table.

    Consider the following scenario:

    // PARENT TABLE
    CREATE TABLE TableA
    (
       ID INT PRIMARY KEY
    );
    
    // CHILD TABLE
    CREATE TABLE TableB
    (
       ID INT PRIMARY KEY,
       TableA_ID INT,
       CONSTRAINT tb_FK FOREIGN KEY (TableA_ID) REFERENCES TableA(ID)
    );
    
    
    // RECORDS OF PARENT TABLE
    INSERT INTO TableA (ID) VALUES (1);
    INSERT INTO TableA (ID) VALUES (2);
    
    // RECORDS OF CHILD TABLE
    INSERT INTO TableB (ID, TableA_ID) VALUES (1,1);
    INSERT INTO TableB (ID, TableA_ID) VALUES (2,1);
    INSERT INTO TableB (ID, TableA_ID) VALUES (3,2);
    

    If you execute the statements above, it will not fail because none of them violates the referential integrity rule.

    Try executing the following statement:

    INSERT INTO TableB (ID, TableA_ID) VALUES (3,4);
    

    It fails because 4 which is the value of TableA_ID to be inserted doesn't exist on Table1.ID. Foreign Keys preserved referential integrity between the records.

提交回复
热议问题