当从父表中删除该行时,如果子表中使用了该行的数据,那么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 父表中删除一行会发生什么?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!