目录
关联查询:将多个表联合起来进行查询,主要有内连接、左连接、右连接、全连接(外连接)
#数据准备
create table dept3(
id int primary key auto_increment,
name varchar(20)
);
insert into dept3
values
(null,'财务部'),(null,'人事部'),(null,'科技部'),(null,'销售部');
create table emp3(
id int primary key auto_increment,
name varchar(20),
did int
);
insert into emp3
values
(null,'刘备',1),(null,'关羽',2),(null,'张飞',3),(null,'赵云',5);
1、笛卡尔查询
select * from dept3,emp3;
#查询的结果是两张表相乘的结果,称之为笛卡尔积查询
#如果左边表有m条数据,右边表有n条数据,则得到m*n条数据
#笛卡尔积查询没有考虑两张表的对应关系,所以结果中包含大量错误的数据,无法直接使用。
#虽然通常不会直接使用,但笛卡尔积查询是其他多表查询的基础,需要了解
2、内连接查询
#可以在笛卡尔积查询的基础上,基于外键字段筛选出正确的数据
select * from dept3,emp3 where emp3.did = dept3.id;
#内连接查询也可以通过专用的语法实现
select * from dept3 inner join emp3 on emp3.did = dept3.id;
#内连接查询只能查询到两张表中都有对应数据的记录。
#对于左边表有而右边表没有数据 和 右边表有而左边表没有的数据 都不会被查询到。
3、外连接查询
a.左外连接查询
在内连接的基础上增加左边表有而右边表没有的记录
select * from dept3 left join emp3 on emp3.did = dept3.id;
b.右外连接查询
在内连接的基础上增加了右边表有而左边表没有的记录
select * from dept3 right join emp3 on emp3.did = dept3.id;
c.全外连接查询
在内连接的基础上增加 左边表有右边表没有的数据 和 右边表有左边表没有的数据
select * from dept3 full join emp3 on emp3.did = dept3.id;
mysql不支持全外连接查询,在mysql中需要使用union操作间接完成全外连接查询
select * from emp3 left join dept3 on emp3.did = dept3.id
union
select * from emp3 right join dept3 on emp3.did = dept3.id;