當從父表中刪除該行時,如果子表中使用了該行的數據,那麼MySQL將因FOREIGN KEY約束失敗而拋出錯誤。可以用「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`))
以上是如果我從 MySQL 父表中刪除一行會發生什麼事?的詳細內容。更多資訊請關注PHP中文網其他相關文章!