当两个表通过 MySQL FOREIGN KEY 连接时,我们如何说子表中的数据完整性得到了维护?
mysqlmysqli database
实际上,外键强制执行引用完整性,这有助于我们自动维护数据的一致性和完整性。可以通过名为"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)
现在,假设我们尝试在‘orders’表中插入一个不存在的客户的值(‘customer’表中不存在 id 10),那么 MySQL 会因为外键约束失败而抛出如下错误。
mysql> insert into orders values(400, 'Notebook',10); ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`query`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`id`) REFERENCES `customer` (`id`))