Foreign key constraint error in MySQL: "Error 1452: Cannot add or update child row"
When inserting data into a child table, foreign key constraints ensure that the data referenced in the parent table exists. However, if this constraint is violated, an error occurs, as shown in the following query:
<code class="language-sql">INSERT INTO Ordrelinje (Ordre, Produkt, AntallBestilt) VALUES (100, 1, 5);</code>
Understanding error
The error "Error 1452: Unable to add or update child row: foreign key constraint failed" indicates that there is no row in the parent table that matches the specified foreign key value. In this example, there is no Ordre with OrderID 100.
Solve the problem
To resolve this error, you must first ensure that the referenced data exists in the parent table:
<code class="language-sql">INSERT INTO Ordre (OrdreID, KundeID) VALUES (100, 200);</code>
Once the parent table has the necessary data, you can insert data into the child table without encountering foreign key constraint errors:
<code class="language-sql">INSERT INTO Ordrelinje (Ordre, Produkt, AntallBestilt) VALUES (100, 1, 5);</code>
Foreign key relationship
Foreign key relationships establish links between tables, ensuring data integrity and preventing data manipulation anomalies. The child table contains a column that references a column in the parent table, creating a parent-child relationship.
Enforce foreign key constraints
Default database settings usually enforce foreign key constraints. If a violation occurs, the database will not allow data manipulation operations to proceed.
The above is the detailed content of MySQL Foreign Key Constraint Error 1452: How to Fix 'Cannot add or update a child row'?. For more information, please follow other related articles on the PHP Chinese website!