ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

后端 未结 21 1738
野性不改
野性不改 2020-11-22 07:01

I have created tables in MySQL Workbench as shown below :

ORDRE table:

CREATE TABLE Ordre (
  OrdreID   INT NOT NULL,
  OrdreDato DA         


        
相关标签:
21条回答
  • 2020-11-22 07:57

    Your ORDRELINJE table is linked with ORDER table using a foreign key constraint constraint Ordrelinje_fk foreign key(Ordre) references Ordre(OrdreID) according to which Ordre int NOT NULL, column of table ORDRELINJE must match any Ordre int NOT NULL, column of ORDER table.

    Now what is happening here is, when you are inserting new row into ORDRELINJE table, according to fk constraint Ordrelinje_fk it is checking ORDER table if the OrdreID is present or not and as it is not matching with any OrderId, Compiler is complaining for foreign key violation. This is the reason you are getting this error.

    Foreign key is the primary key of the other table which you use in any table to link between both. This key is bound by the foreign key constraint which you specify while creating the table. Any operation on the data must not violate this constraint. Violation of this constraint may result in errors like this.

    Hope I made it clear.

    0 讨论(0)
  • 2020-11-22 07:58

    You are getting this constraint check because Ordre table does not have reference OrdreID provided in insert command.

    To insert value in Ordrelinje, you first have to enter value in Ordre table and use same OrdreID in Orderlinje table.

    Or you can remove not null constraint and insert a NULL value in it.

    0 讨论(0)
  • 2020-11-22 07:58

    ill squeeze this in here: my case was trying to create a like for a post which dint exist; while committing to database the error was raised. solution was to first create the post then like it. from my understanding if the post_id was to be saved in the likes table it had to first check with posts table to ascertain existence. i found it better to have it this way since its more logical to me that way..

    0 讨论(0)
提交回复
热议问题