如果我删除 MySQL 父表中的某一行,会发生什么?
如果从父表中删除行,而该行的 data 在子表中使用,则 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`))
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP