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

เมื่อเชื่อมตาราง 2 ตารางด้วย FOREIGN KEY แล้ว ข้อมูลใน Child table ยังคงสมบูรณ์อย่างไร

Foreign keys บังคับใช้ referential integrity ช่วยรักษาความสอดคล้องและความสมบูรณ์ของข้อมูลโดยอัตโนมัติ เข้าใจได้จากตัวอย่าง 'customer' (parent) และ 'orders' (child) ไม่สามารถสร้างออเดอร์สำหรับลูกค้าที่ไม่มีอยู่ได้

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    |
+-----------+-------------+------+

ลองเพิ่มค่าใน 'orders' สำหรับลูกค้าที่ไม่มีอยู่ (id 10 ไม่มีใน 'customer'):

mysql> INSERT INTO orders VALUES(400, 'Notebook', 10);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails...