当前位置:网站首页>sql 外键约束【表关系绑定】
sql 外键约束【表关系绑定】
2022-07-31 05:15:00 【为今天而努力】
外键
外键必须是表中的一个字段但不一定是该表的主键,但要对应的必须是另一张表的主键,外键的主要作用就是啊要保持数据的完整性,定义外键后不允许删除在另外一张表中具有关联关系的行【一条数据】。
- 主表(父表):主键所在的表即为主表。
- 从表(子表):外键所在的表即为从表。
什么时候使用外键约束
当两张表之间有有关联时可以采用外键约束进行绑定。
示例:有两张表分别为 tb_book【书 】 、 tb_reader【阅读】 ,显然没有书就无法阅读,所以 tb_book 为主表,tb_reader 为从表
// 创建tb_book
CREATE TABLE tb_book(
id int primary key auto_increment,
book_name varchar(50));
// 创建tb_reader
CREATE TABLE tb_reader(
id int primary key auto_increment,
bookId int,
constraint fk_book_id foreign key(bookId) references tb_book(id));
insert into book (book_name) values('喀尔巴阡古堡');
// 正确操作
insert into reader (readPage) values(45);
insert into reader (bookId, readPage) values (1, 30);
// 错误操作
delete from book where id = 1;
insert into reader (bookId, readPage) values (2, 30);
使用外键时注意
- 一个表可以有一个或者多个外键。
- 外键对应的是参照完整性,一个表的外键可以为空值,如果不为空值,则每一个外键的值必须是另一个表中主键的某一个值,否则会提示如下错误:
insert into reader (bookId, readPage) values (30, 1);
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`test_db`.`reader`,
CONSTRAINT `fk_book_id` FOREIGN KEY (`bookId`) REFERENCES `book` (`id`))
- 如果删除在另一张表中具有关联关系的行【一条数据】则会出一下异常:
delete from book where id = 1;
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`test_db`.`reader`,
CONSTRAINT `fk_book_id` FOREIGN KEY (`bookId`) REFERENCES `book` (`id`))
如果创建时没有添加外键约束可以使用 alter table add 添加
alter table reader add constraint fk_book_id foreign key(bookNameId) references tb_book(id);
边栏推荐
- Fragmented NFT (Fractional NFT)
- On the side of Ali, tell me what are the application scenarios of message middleware you know?
- Eternal blue bug reappears
- Build DVWA with phpstudy
- flutter 混合开发 module 依赖
- GUCCI, LV and other luxury giant universe how to layout yuan, other brands should keep up with?
- [uiautomation] Get WeChat friend list (stored in txt)
- MySQL-如何分库分表?一看就懂
- MySql创建数据表
- GUCCI、LV等奢侈品巨头如何布局元宇宙的,其他品牌应该跟上吗?
猜你喜欢
随机推荐
About integrating superset into your own project
The MySQL database in Alibaba Cloud was attacked, and the data was finally recovered
DeFi 项目中的治理Token
Build DVWA with phpstudy
了解SSRF,这一篇就足够了
gin框架学习-JWT认证
leetcode-每日一题745. 前缀和后缀搜索(哈希和字典树)
在kali上搭建vulhub漏洞靶场
Error: Cannot find module 'D:\Application\nodejs\node_modules\npm\bin\npm-cli.js'
GUCCI, LV and other luxury giant universe how to layout yuan, other brands should keep up with?
Linux修改MySQL数据库密码
使用ps | egrep时过滤排除掉egrep自身
MySql创建数据表
【云原生】SQL(及存储过程)跑得太慢怎么办?
腾讯云轻量服务器删除所有防火墙规则
什么是 GameFi?
一文速学-玩转MySQL获取时间、格式转换各类操作方法详解
leetcode-1833. 雪糕的最大数量(排序+贪心)
MySQL高级语句(一)
Using IIS10 to build an asp website in win11