一、什么是多表关联查询?
定义:查询数据来源于多张表。
1、内连接(基本内连接和隐藏内连接)
2、左连接(左外连接)
3、右连接(右外连接)
4、全外连接(全外连接)
=============================================
关系:
E:/youdaofanyi/weixinobU7Vjpxg5IHOu_HmnT5kAiN7rw0/464256e4c6b64b98bafadfcd7e2e34bd/1628673025%281%29.png
建表数据
1、首先要建立两个表 dept 和 emp 表
E:/youdaofanyi/weixinobU7Vjpxg5IHOu_HmnT5kAiN7rw0/afe2b6bcd76f493aa185610a91e8a303/clipboard.png
dept 部分编号
dept_name 部门名称
emp表
E:/youdaofanyi/weixinobU7Vjpxg5IHOu_HmnT5kAiN7rw0/68ab10a6a35449068052c0bebd5afd5b/clipboard.png
sid 员工编号
name 员工姓名
age 员工年龄
woekrtime_start 入职时间
incoming 薪资
dept2 部门编号
两个表的关联关系: dept1= dept2
===================================
一、内连接
查询两个表共有的关联数据
普通内连接 隐藏内连接
普通内连接:
格式:select * from 表1 inner join 表2 on 表1.关联字段1=表2.关联字段2
案例1:select * from dept inner join emp on dept.dept1=emp.dept2 ;
案例2:select name,dept_name from dept inner join emp on dept.dept1=emp.dept2 where sid=1789 ;
隐藏内连接:
格式:select * from 表1,表2 where 表1.关联字段1=表2.关联字段2
select * from dept,emp where dept.dept1=emp.dept2 ;
二、左连接
以左表为主(显示完整的左表),游标关联的数据就显示,没有的数据就以null显示
格式:
select * from 表1 left join 表2 on 表1.关联字段1=表2.关联字段2 ;
案例:
select * from dept left join emp on dept.dept1=emp.dept2 ;
三、右连接
右表是以右表数据为主(显示整个右表)左表有关联的数据就显示,没有就以null值显示。
格式:select * from 表1 right join 表2 on 表1.关联字段1=表2.关联字段2 ;
select* from dept right join emp on dept.dept1=emp.dept2 ;
四、左表独有数据
左表中独有的数据显示,(方法,左独有,以右表字段为空查询)
格式:select * from 表1 left join 表2 on 表1.关联字段1=表2.关联字段2 where 右表字段 is null
select * from dept left join emp on dept.dept1=emp.dept2 where name is null;
五、右表独有数据
右表中独有的数据显示,(方法,右独有,以左表字段为空查询)
格式:select * from 表1 right join 表2 on 表1.关联字段1=表2.关联字段2 where 左表字段 is null
案例:
select * from dept right join emp on dept.dept1=emp.dept2 where dept1 is null;
六、左表独有数据+右表独有数据
union 拼接
左独有 union
select * from dept left join emp on dept.dept1=emp.dept2 where name is null
union
select * from dept right join emp on dept.dept1=emp.dept2 where dept1 is null;
七、全连接
方法一:左独有+右独有+内连接
select * from dept left join emp on dept.dept1=emp.dept2 where name is null
union
select * from dept right join emp on dept.dept1=emp.dept2 where dept1 is null
UNION
select * from dept inner join emp on dept.dept1=emp.dept2 ;
方法二:左连接+右独有
select * from dept left join emp on dept.dept1=emp.dept2 UNION
select * from dept right join emp on dept.dept1=emp.dept2 where dept1 is null ;
方法三:右连接+左独有
select * from dept right join emp on dept.dept1=emp.dept2 UNION
select * from dept left join emp on dept.dept1=emp.dept2 where name is null ;
=============================================
总结
普通内连接:
select * from 表1 inner join 表2 on 表1 的关联字段=表2的关联字段 ;
隐藏内连接:
select * from 表1 , 表2 where 表1 的关联字段=表2的关联字段 ;
左连接
select * from 表1 left join 表2 on 表1 的关联字段=表2的关联字段 ;
右连接:
select * from 表1 right join 表2 on 表1 的关联字段=表2的关联字段 ;
左独有数据:
select * from 表1 left join 表2 on 表1 的关联字段=表2的关联字段 where 右表字段为空;
右独有数据:
select * from 表1 right join 表2 on 表1 的关联字段=表2的关联字段 where 左表字段为空;
全外连接:
1、左独有+右独有+内连接
2、左连接+右独有
3、右连接+左独有
|
|