當兩個表用MySQL外部索引鍵連線時,我們如何說子表中的資料完整性得到維護?


實際上,外部索引鍵強制執行參照完整性,這有助於我們自動維護資料的 consistency(一致性)和完整性。這可以用名為“customer”(客戶)和“orders”(訂單)的兩個表為例來說明。“customer”是父表,“orders”是子表。我們不能為不存在的客戶建立訂單。可以透過如下方式在兩個表中插入值來演示:

mysql> Select * from Customer;
+----+--------+
| id | name   |
+----+--------+
| 1  | Gaurav |
| 2  | Raman  |
| 3  | Harshit|
| 4  | Aarav  |
+----+--------+
4 rows in set (0.00 sec)
mysql> Select * from orders;
+-----------+-------------+------+
| order_id  | product     | id   |
+-----------+-------------+------+
| 100       | Notebook    | 1    |
| 110       | Pen         | 1    |
| 120       | Book        | 2    |
| 130       | Charts      | 2    |
+-----------+-------------+------+
4 rows in set (0.00 sec)

現在,假設如果我們嘗試為不存在的客戶(id 10 不存在於“customer”表中)在“orders”表中插入值,則由於外部索引鍵約束失敗,MySQL 會丟擲如下錯誤。

mysql> insert into orders values(400, 'Notebook',10);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`query`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`id`) REFERENCES `customer` (`id`))

更新於:2020年1月28日

153 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.