如果我从 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`))

更新时间:28-Jan-2020

1K+ 浏览量

开启你的职业生涯

完成课程以获得认证

开始
广告