【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禁止了。
外键的约束,有时候也不是个好用的东西,因为当两张表分别为订单和商品的时候,可能会过于约束,导致商品不能下架。
那么我们怎么解决这种过度的约束呢?
我们可以给商品表加一列,【是否有效】,这样,已经下单的订单,就算关联了商品,我们也可以通过【是否有效】这一栏,来判断商品是否下架。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值