当前位置:网站首页>多表操作-外键约束
多表操作-外键约束
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);
边栏推荐
- Mistakes the project manager should not make
- Go learning notes
- 动态样式绑定--style 和 class
- 为什么vscode用久了电脑速度变慢?
- 翻转链表II[翻转链表3种方式+dummyHead/头插法/尾插法]
- Binary search tree (1) - concept and C language implementation
- vncserver: Failed command ‘/etc/X11/Xvnc-session‘: 256!
- Scene 299
- B_QuRT_User_Guide(35)
- FreeRTOS记录(九、一个裸机工程转FreeRTOS的实例)
猜你喜欢

MFC界面库BCGControlBar v33.0 - 桌面警报窗口、网格控件升级等

Document contains & conditional competition

阿里kube-eventer mysql sink简单使用记录

Lumiprobe生物素亚磷酰胺(羟脯氨酸)说明书

1.微信小程序页面跳转方法总结;2. navigateTo堆栈到十层不跳转问题

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

Lumiprobe biotin phosphimide (hydroxyproline) instructions

Basic components of STL

Golang应用 ━━ 安装、配置与使用hugo博客系统

PHP require/include 区别
随机推荐
Software engineering UML drawing
开发技术-获取10分钟前的时间
A complete collection of vulnerability scanning tools. Mom doesn't have to worry that I won't find any more vulnerabilities
Is it safe to open an account for online stock trading!?
[原创]用代码dialog 高度 宽度无法屏幕屏幕问题
Study on lumiprobe dye NHS ester BDP FL NHS ester
C文件指针
第81场双周赛
北京大学ACM Problems 1002:487-3279
【微服务~Nacos】Nacos之配置中心
jfinal中如何使用过滤器监控Druid监听SQL执行?
Peking University ACM problems 1005:i think I need a houseboat
Qiao NPMS: search for NPM packages
大学生研究生毕业找工作,该选择哪个方向?
北京大学ACM Problems 1003:Hangover
MySQL:SQL概述及数据库系统介绍 | 黑马程序员
Study on lumiprobe modified triphosphate biotin-11-utp
Solve the problems of Devops landing in complex environment with various tools with full stack and full function solutions
1. Introduction to generating countermeasures network
北京大学ACM Problems 1004:Financial Management






