多表关联查询

1.多表关联查询

多表关联查询有五种分别是:

1. 交叉连接(数据库底层的实现原理,笛卡尔积现象) cross join:
select * from emp cross jion dept; 
select * from emp,dept;
2. 外连接(outer join)
分为左外链接和右外连接
左外连接:
select * from left [outer] join dept on (emp.deptid=dept.id)
右外连接:
select * from right [outer] join dept on (emp.deptid=dept.id)

3. 内连接(inner join)
select * from emp,dept where emp.deptid=dept.id;
select * from emp inner join dept on(emp.deptid=dept.id)
4. 自然连接
select * from emp natural join dept;
5. 自连接(自连接的查询效率没有内外连接的效率高)
外键在约束自身的某个字段
子查询

2.表与表的关联关系

1:1
1:n
m:n
外键约束 外键名称可以不写系统自动生成 不会重复 自己写方面删除
[constraint] foreign key(外键名称 FK) references 从表(id PK) [on delete restrict/cascade/set null(部门已经解散,员工等待安排) on update restrict]
已存在的表添加外键
alter table tName add [constraint] foreign key(外键名称 FK) references 从表 (id PK)
删除外键
alter table tName drop [constraint] foreign key(外键名称 FK) references 从 表 (id PK)

猜你喜欢

转载自blog.csdn.net/qwerlol123456/article/details/80816006