當從父表中刪除該行時,如果子表中使用了該行的數(shù)據(jù),那么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)
登錄后復制
現(xiàn)在,假設我們嘗試從父表“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 父表中刪除一行會發(fā)生什么?的詳細內容,更多請關注www.92cms.cn其它相關文章!