如果我们使用内连接来查询数据:
使用inner join - on子句:显示的是所有匹配的信息
select *
from emp e
inner join dept d
on e.deptno = d.deptno;

inner join - on子句缺点:
- 部门编号为40的,没有显示员工信息,将不会在查询中显示
- 某员工没有部门编号信息,将不会显示在查询中
所以,使用内连接来查询的话,有时候显示的数据是不全的。如果我们希望两张表中没有匹配的信息也显示出来,可以使用外连接查询。
外连接包括:
- 左外连接:
left outer join - 右外连接:
right outer join
PS:在使用的过程中,outer可以省略不写。
使用左外连接,左边那个表的信息,即使不匹配也可以显示出数据;
使用右外连接,右边那个表的信息,即使不匹配也可以显示出数据。
全外连接:full outer join
这个语法会展示左右表全部不匹配的数据,但是在mysql中不支持,在oracle中支持。
select *
from emp e
full outer join dept d
on e.deptno = d.deptno;
返回1064语法错误:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘full outer join dept d
on e.deptno = d.deptno’ at line 3
但是可以使用语法union实现这个逻辑,关键字union表示取左右外连接查询的并集。
1.用union取并集,会自动去重,因此效率低。
select *
from emp e
left outer join dept d
on e.deptno = d.deptno
union -- 并集-去重-效率低
select *
from emp e
right outer join dept d
on e.deptno = d.deptno;
2.用union all取并集,不去重,因此效率高。
select *
from emp e
left outer join dept d
on e.deptno = d.deptno
union all -- 并集-不去重-效率高
select *
from emp e
right outer join dept d
on e.deptno = d.deptno;
mysql对集合操作支持较弱,只支持并集操作,交集和差集操作是不支持的(oracle中是支持的)。



















