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

เกิดอะไรขึ้นเมื่อลบแถวจากตาราง Parent ใน MySQL

ขณะลบแถวจากตาราง parent หากข้อมูลของแถวนั้นถูกใช้ในตาราง child MySQL จะแสดงข้อผิดพลาดเนื่องจาก FOREIGN KEY constraint ล้มเหลว สามารถเข้าใจได้จากตัวอย่าง 2 ตาราง 'customer' (parent) และ 'orders' (child) ไม่สามารถลบแถวที่ถูกใช้ใน child table 'orders' จากตาราง 'customer' ได้

mysql> SELECT * FROM Customer;
+----+--------+
| id | name   |
+----+--------+
| 1  | Gaurav |
| 2  | Raman  |
| 3  | Harshit|
| 4  | Aarav  |
+----+--------+

mysql> SELECT * FROM orders;
+----------+----------+------+
| order_id | product  | id   |
+----------+----------+------+
| 100      | Notebook | 1    |
| 110      | Pen      | 1    |
| 120      | Book     | 2    |
| 130      | Charts   | 2    |
+----------+----------+------+

ลองลบแถวที่ id = 1 หรือ 2 (ถูกใช้ใน child table) จาก parent table 'customer':

mysql> DELETE FROM customer WHERE id = 1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails...

mysql> DELETE FROM customer WHERE id = 2;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails...