外键
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NIOUtu2r-1686801322665)(C:\Users\10585\AppData\Roaming\Typora\typora-user-images\image-20230615101359094.png)]
有外键的为从表。
逻辑外键:数据库层面没有建立关系,无法保证数据的一致性何完整性。
物理外键:设置后父表有关联无法删除(删除/更新行为)。
--添加外键
alter table [表名] add constraint [外键名] foreign key ([添加外键字段名]) references [表名](id)
on update [行为] on delete [行为]
--删除外键
alter table [表名] drop foreign key [外键名]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zvqkIV2y-1686801322666)(C:\Users\10585\AppData\Roaming\Typora\typora-user-images\image-20230615102652440.png)]
多表查询
多表关系
- 一对一 在任意一方加外键(用于单表拆分)
- 多对多 学生—课程 中间表 关联双方主键
- 一对多 部门(主键一)–>员工(外键多)
多表查询概述
--多表查询 笛卡尔积AB集合所有组合
select * from A,B;
--加条件消除
select * from A,B where A.id=B.id;
内连接
查交集
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0tAOTI4e-1686801322666)(C:\Users\10585\AppData\Roaming\Typora\typora-user-images\image-20230615111500728.png)]
- 隐式内连接
select * from A,B where 条件...;
- 显式内连接
select * from A join B on 条件...;
外连接
- 左外(左表所有数据加交集部分)
select * from A left join B on 条件...;
- 右外
select * from A left join B on 条件...;
自连接
select * from A join B on 条件...;
联合查询
返回列数,字段类型保持一致
--去掉“all”去重
select * from A where 条件...
union all
select * from A where 条件...
子查询
select * from A where 条件…
union all
select * from A where 条件…
### 子查询