如果我從 MySQL 父表中刪除一行將會發生什麼?
從父表中刪除行時,如果該行的記錄已在子表中使用,那麼 MySQL 將丟擲錯誤,因為外部索引鍵約束已失效。可以使用兩個表“customer”和“orders”的示例來理解這一點。此處,“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)
現在,假設我們嘗試從父表“customer”中刪除具有 id = 1 或 id =2 的行(因為這兩行已在子表中使用),則 MySQL 會由於外部索引鍵約束失效而丟擲如下錯誤。
mysql> Delete from customer where id = 1; ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`query`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`id`)REFERENCES `customer` (`id`)) mysql> Delete from customer where id = 2; ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`query`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`id`)REFERENCES `customer` (`id`))
廣告