当前位置:网站首页>多表操作-外键约束
多表操作-外键约束
2022-06-30 20:38:00 【汤键.TJ】
目录
为何需要外键约束
当表与表之间的数据有相关联性时
- 如果没有相关的数据约束,则无法保证数据的准确性
外键约束的作用:
- 让表与表之间产生关联关系,从而保证数据的准确性
外键约束使用
建表时添加外键约束
- create table 表名(
- 列名 数据类型 约束
- .....
- constraint 外键名 foreign key (本表外键列名) references 主表名 (主表主键列名)
- )
删除外键约束
- alter table 表名 drop foreign 外键名
建表后单独添加外键约束
- alter table 表名 add
- constraint 外键名 foreign key (本表外键列名) references 主表名(主键列名)
实例演示
首先创建2表,并使用外键约束



CREATE TABLE user( id INT PRIMARY KEY auto_increment, name VARCHAR(40) NOT NULL ); INSERT INTO user VALUES (NULL,'张三'),(NULL,'李四'); CREATE TABLE ouser( id INT PRIMARY KEY auto_increment, number VARCHAR(20) NOT NULL, uid INT, -- 外键列 CONSTRAINT ou FOREIGN KEY (uid) REFERENCES user (id) ); INSERT INTO ouser VALUES (NULL,'hm1',1),(NULL,'hm2',1),(NULL,'hm3',2),(NULL,'hm4',2);进行错误测试


-- 添加一个ouser 但是没有对应的user,会添加失败 INSERT INTO ouser VALUES (NULL,'hm5',3); -- 删除李四用户会删除失败 DELETE FROM user WHERE name='李四';删除外键约束

添加外键约束

-- 删除外键约束 ALTER TABLE ouser DROP FOREIGN KEY ou; -- 添加外键约束 ALTER TABLE ouser ADD CONSTRAINT ou FOREIGN KEY (uid) REFERENCES user(id);
边栏推荐
猜你喜欢

Failed to configure a DataSource: ‘url‘ attribute is not specified and no embedded datasource could

片荒吗?不用下载直接在线免费看的资源来了!2022年收藏夹必须有它!

On the charm of code language

Study on lumiprobe dye NHS ester BDP FL NHS ester

PHP获取Opcode及C源码

Study on lumiprobe modified triphosphate biotin-11-utp

基于开源流批一体数据同步引擎ChunJun数据还原—DDL解析模块的实战分享

左值引用和右值引用

Label Contrastive Coding based Graph Neural Network for Graph Classification

Lumiprobe细胞生物学丨DiA,亲脂性示踪剂说明书
随机推荐
Go language identifier and package name specification
Lumiprobe生物素亚磷酰胺(羟脯氨酸)说明书
请问海量数据如何去取最大的K个
FreeRTOS记录(九、一个裸机工程转FreeRTOS的实例)
北京大学ACM Problems 1000:A+B Problem
A complete collection of vulnerability scanning tools. Mom doesn't have to worry that I won't find any more vulnerabilities
unittest自动测试多个用例时,logging模块重复打印解决
Is the project manager a leader? Can you criticize and blame members?
1.微信小程序页面跳转方法总结;2. navigateTo堆栈到十层不跳转问题
STL的基本组成部分
coredns 修改upstream
Huffman Tree (1) Basic Concept and C - language Implementation
Halcon knowledge: check the measurement objects [1]
qiao-npms:搜索npm包
亚马逊在阿拉伯联合酋长国限制LGBTQ相关的搜索和产品销售
AVL平衡二叉树(一) - 概念与C语言实现
Lumiprobe蛋白质定量丨QuDye 蛋白定量试剂盒
偏向锁/轻量锁/重级锁锁锁更健康,上锁解锁到底是怎么完成实现的
Playwright - scroll bar operation
What bank card do you need to open an account online? In addition, is it safe to open an account online now?






