Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ข้อผิดพลาด MySQL 1452 - Foreign Key Constraint Fails


Error 1452 เกิดเมื่อ insert ข้อมูลลงตารางลูก (Child table) ที่มี Foreign Key อ้างอิงตารางแม่ (Parent table) แต่ข้อมูลในตารางแม่ยังไม่มี

สร้างตารางและ FK:

mysql> CREATE table ForeignTable ( id int, name varchar(200), Fk_pk int ); Query OK, 0 rows affected (0.43 sec)
mysql> CREATE table primaryTable1 ( Fk_pk int, DeptName varchar(200), Primary key(Fk_pk) ); Query OK, 0 rows affected (0.48 sec)
mysql> alter table ForeignTable add constraint constFKPK foreign key(Fk_pk) references primaryTable1(Fk_pk); Query OK, 0 rows affected (1.57 sec)

พยายาม insert ลง ForeignTable ก่อน:

mysql> INSERT into ForeignTable values(1,'John',1);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`business`.`foreigntable`, CONSTRAINT `constFKPK` FOREIGN KEY (`Fk_pk`) REFERENCES `primarytable1` (`fk_pk`))

วิธีแก้: Insert ข้อมูลในตารางแม่ (primaryTable1) ก่อน

mysql> INSERT into primaryTable1 values(1,'ComputerScience'); Query OK, 1 row affected (0.14 sec)
mysql> INSERT into ForeignTable values(1,'John',1); Query OK, 1 row affected (0.13 sec)

ตรวจสอบข้อมูลทั้งสองตาราง:

mysql> SELECT * from ForeignTable;
+------+------+-------+
| id   | name | Fk_pk |
+------+------+-------+
| 1    | John | 1     |
+------+------+-------+
mysql> SELECT * from primarytable1;
+-------+-----------------+
| Fk_pk | DeptName        |
+-------+-----------------+
| 1     | ComputerScience |
+-------+-----------------+

สรุป: ต้องมีข้อมูลในตารางอ้างอิง (Referenced table) ก่อนจึงจะ insert ลงตารางที่มี FK ได้