如果我从MySQL父表中删除一行会发生什么?
在从父表中删除行时,如果该行的数据在子表中使用,则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将由于foreign key约束失败而抛出以下错误。
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 教程