Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Lỗi MySQL 1452: Cannot add or update child row - foreign key constraint fails?


Lỗi xảy ra khi chèn vào bảng con (child) giá trị khóa ngoại không tồn tại trong bảng cha (parent).

Tạo bảng cha (ParentDemo) - có PRIMARY KEY

mysql> CREATE TABLE ParentDemo (
    -> FKPK INT,
    -> Name VARCHAR(100),
    -> PRIMARY KEY(FKPK)
    -> );
Query OK, 0 rows affected (0.57 sec)

Tạo bảng con (ChildDemo)

mysql> CREATE TABLE ChildDemo (
    -> Id INT,
    -> FKPK INT
    -> );
Query OK, 0 rows affected (0.86 sec)

Thêm FOREIGN KEY

mysql> ALTER TABLE ChildDemo
    -> ADD CONSTRAINT ConstChild
    -> FOREIGN KEY (FKPK) REFERENCES ParentDemo(FKPK);
Query OK, 0 rows affected (1.97 sec)

Chèn vào bảng con khi bảng cha rỗng → LỖI 1452

mysql> INSERT INTO ChildDemo VALUES(1,3);
ERROR 1452 (23000): Cannot add or update a child row:
a foreign key constraint fails (`business`.`childdemo`,
CONSTRAINT `ConstChild` FOREIGN KEY (`FKPK`)
REFERENCES `parentdemo` (`fkpk`))

Nguyên nhân: Bảng ParentDemo không có hàng nào với FKPK=3. Foreign key yêu cầu giá trị tham chiếu phải tồn tại ở bảng cha.

Foreign key relationships involve a parent table that holds the central data values, and a child table with identical values pointing back to its parent. The FOREIGN KEY clause is specified in the child table. It will reject any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table.