连接查询 - 内连接 作用: 查询两张表的交集数据
内连接查询语法:
-- 隐式内连接
select 字段列表 from 表1, 表2 where 条件 ....;
-- 显式内连接
select 字段列表 from 表1 [inner] join 表2 on 连接条件 ...;
内连接查询的是两张表交集的部分
内连接演示:
创建emp表和dept表在上一篇博客有写到,这里就不再提供了
-- 1.查询每一个员工的姓名以及关联的部门的名称(隐式内连接)
-- 表结构: emp ,dept
-- 连接条件: emp.dept_id = dept.id
-- 写法1
select emp.name,dept.name from emp,dept where emp.dept_id = dept.id;
-- 写法2
select e.name,d.name from emp e,dept d where e.dept_id = d.id;
-- 2.查询每一个员工的姓名以及关联的部门的名称(显式内连接)
-- 表结构: emp ,dept
-- 连接条件: emp.dept_id = dept.id
select e.name,d.name from emp e inner join dept d on e.dept_id = d.id;
-- inner 可以省略
select e.name,d.name from emp e join dept d on e.dept_id = d.id;
连接查询 - 外连接
外连接查询语法:
左外连接
select 字段列表 from 表1 left [outer] join 表2 on 条件 ...;
-- 相当于查询表1(左表)的所有数据包含表1和表2交集部分的数据
右外连接
select 字段列表 from 表1 right [outer] join 表2 on 条件 ...;
-- 相当于查询表1(右表)的所有数据包含表1和表2交集部分的数据
外连接演示
-- 1.查询emp表所有的数据,和对应的部门信息(左外连接)
-- 表结构: emp,dept
-- 连接条件: emp.dept_id = dept.id
select e.*,d.name from emp e left join outer dept d on emp.dept_id = dept.id;
-- outer 可以省略
select e.*,d.name from emp e left join dept d on emp.dept_id = dept.id;
-- 2.查询dept表所有数据,和对应的员工信息(右外连接)
select d.*,e.* from emp e right join dpet d on emp.dept_id = dept.id;
连接查询 — 自连接
自连接查询语法:
select 字段列表 表A 别名A join 表A 别名B on 条件...;
自连接查询,可以是内连接查询,也可以是外连接查询
自连接代码演示
-- 1. 查询员工及其所属领导的名字
-- 表结构: emp
select a.name,b.name from emp a,emp b where a.managerid = b.id;
-- 2.查询所有员工及其领导的名字,如果员工没有领导,也需要查询出来
select a.name '员工',b.name '领导' from emp a left join emp b on a.mangerid = b.id;
联合查询 - union union all
对于 union 查询,就是把多次查询的结果合并起来,形成一个新的查询结果集
语法:
select 字段列表 from 表A ...
union [all]
select 字段列表 from 表B ...;
注意&