mysql中foreign key的使用注意

发布日期:2023-05-26 浏览次数:1

1、用于约束表中的字段,必须是另一个表中某个字段所存在的值。

2、在另一个表中,这个列不一定是主键,但必须是唯一性索引,否则会创建失败。

实例

mysql> create table orders (id int(11) primary key ,userId int(11) ,  FOREIGN KEY (userId) REFERENCES user(id) );Query OK, 0 rows affected, 2 warnings (0.06 sec) mysql> insert orders values(1,3);ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`t`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `user` (`id`)) mysql> insert orders values(1,1);Query OK, 1 row affected (0.01 sec)
如果您有什么问题,欢迎咨询技术员 在线沟通