当前位置:网站首页>多表操作-外键约束
多表操作-外键约束
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);
边栏推荐
- Qt和其它GUI库的对比
- Deflection lock / light lock / heavy lock lock is healthier. How to complete locking and unlocking
- 大学生研究生毕业找工作,该选择哪个方向?
- 数据库 OLAP、OLTP是什么?相同和不同?适用场景
- Evolution of screen display technology
- Solve the problems of Devops landing in complex environment with various tools with full stack and full function solutions
- 三个火枪手
- STL的基本组成部分
- Binary search tree (1) - concept and C language implementation
- Go learning notes
猜你喜欢
随机推荐
大学生研究生毕业找工作,该选择哪个方向?
Lumiprobe 改性三磷酸盐丨生物素-11-UTP研究
Study on PEGylation of lumiprobe and PEG linker - iodine-peg3-acid
Lumiprobe biotin phosphimide (hydroxyproline) instructions
转:用实际行动赢得别人追随
PHP获取Opcode及C源码
SqlServer 获取字符串中数字,中文及字符部分数据
Go学习笔记
北京大学ACM Problems 1004:Financial Management
Testing principle and precautions of biovendor rage ELISA Kit
maya房子建模
哈夫曼樹(一)基本概念與C語言實現
Failed to configure a DataSource: ‘url‘ attribute is not specified and no embedded datasource could
Is the project manager a leader? Can you criticize and blame members?
断点续传和下载原理分析
Lumiprobe 聚乙二醇化和 PEG 接头丨碘-PEG3-酸研究
Scene 299
【数字IC应届生职业规划】Chap.1 IC行业产业链概述及代表企业大厂汇总
Informatics Olympiad 1362: family problems
Huffman Tree (1) Basic Concept and C - language Implementation












![翻转链表II[翻转链表3种方式+dummyHead/头插法/尾插法]](/img/a8/6472e2051a295f5e42a88d64199517.png)


