当前位置:网站首页>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);
边栏推荐
猜你喜欢
随机推荐
Android软件安全与逆向分析阅读笔记
js中的break与continue退出
MySQL compressed package installation, fool teaching
什么是EVM兼容链?
C language tutorial (3) - if and loop
纯shell实现文本替换
腾讯云轻量服务器删除所有防火墙规则
DeFi 项目中的治理Token
SSH自动重连脚本
GUCCI、LV等奢侈品巨头如何布局元宇宙的,其他品牌应该跟上吗?
MySql创建数据表
在kali上搭建vulhub漏洞靶场
Oracle数据库中的“limit”查询
[Cloud native] Simple introduction and use of microservice Nacos
[swagger close] The production environment closes the swagger method
Memcached :安装
动态规划(一)| 斐波那契数列和归递
vulhub靶场学习日记hackme2
The MySQL database in Alibaba Cloud was attacked, and the data was finally recovered
数据库 | SQL增删改查基础语法






![[swagger close] The production environment closes the swagger method](/img/43/17be22626ba152b33beaf03f92fbec.png)


