700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 【MYSQL】foreign key 外键约束(详解)

【MYSQL】foreign key 外键约束(详解)

时间:2024-03-02 22:36:15

相关推荐

【MYSQL】foreign key 外键约束(详解)

外键是关联不同表之间的一个联接,比如我们现在有两张表:

那么如何设置外键呢?

mysql> create table class(classId int primary key auto_increment,className varchar(20));Query OK, 0 rows affected (0.02 sec)mysql> create table student(studentId int primary key auto_increment,name varchar(20),classId int,-> foreign key (classId) references class(classId));Query OK, 0 rows affected (0.04 sec)mysql> desc student;+-----------+-------------+------+-----+---------+----------------+| Field| Type | Null | Key | Default | Extra|+-----------+-------------+------+-----+---------+----------------+| studentId | int | NO | PRI | NULL | auto_increment || name| varchar(20) | YES || NULL ||| classId | int | YES | MUL | NULL ||+-----------+-------------+------+-----+---------+----------------+3 rows in set (0.01 sec)mysql> desc class;+-----------+-------------+------+-----+---------+----------------+| Field| Type | Null | Key | Default | Extra|+-----------+-------------+------+-----+---------+----------------+| classId | int | NO | PRI | NULL | auto_increment || className | varchar(20) | YES || NULL ||+-----------+-------------+------+-----+---------+----------------+2 rows in set (0.00 sec)

另外需要注意的是,外键关联的必须是另一个表的主键(非空且唯一的键)。

如果一个表中的主键被关联了,那这个表的主键不能被修改/删除:

mysql> update class set classId = 10 where className = '一班';ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`z1`.`student`, CONSTRAINT `student_ibfk_1` FOREIGN KEY (`classId`) REFERENCES `class` (`classId`))mysql> update student set classId = 10 where name = 'z1';ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`z1`.`student`, CONSTRAINT `student_ibfk_1` FOREIGN KEY (`classId`) REFERENCES `class` (`classId`))

为什么不能被修该/删除呢,因为这样就会出现矛盾。所以这样的操作被mysql禁止了。

外键的约束,有时候也不是个好用的东西,因为当两张表分别为订单和商品的时候,可能会过于约束,导致商品不能下架。

那么我们怎么解决这种过度的约束呢?

我们可以给商品表加一列,【是否有效】,这样,已经下单的订单,就算关联了商品,我们也可以通过【是否有效】这一栏,来判断商品是否下架。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。