如果我从 MySQL 父表中删除一行会发生什么?

mysqlmysqli database

从父表中删除行时,如果子表中使用了该行的数据,则 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`))

相关文章