Home > Database > Mysql Tutorial > MySQL Foreign Key Constraint Error 1452: How to Fix 'Cannot add or update a child row'?

MySQL Foreign Key Constraint Error 1452: How to Fix 'Cannot add or update a child row'?

Mary-Kate Olsen
Release: 2025-01-21 05:07:08
Original
331 people have browsed it

MySQL Foreign Key Constraint Error 1452: How to Fix

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>
Copy after login
Copy after login

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>
Copy after login

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>
Copy after login
Copy after login

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.

  • Parent table: contains the primary key value.
  • Child table: has a foreign key value pointing to the parent table.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template