表连接
查询结果分别在两张表中,想要得到完整结果,需要从两张表中找数据
1.内连接
关键字:[inner] join
语法规则:from 表1 [inner] join 表2 on 表1.字段名=表2.字段名
注意:内连接只展示两表之间有关联的内容,如果有一条数据在另一张表中没有与之关联的数据,内连接会舍弃此数据
--使用内连接查询员工id,姓名,工资,部门编号,部门名
select e.employee_id,e.first_name,e.salary,e.department_id,d.department_name from employees e inner join departments d on e.department_id = d.department_id
2.外连接
- 左外连接
关键字:left [outer] join
语法规则:from 表1 left [outer] join 表2 on 表1.字段名 = 表2.字段名
左表的所有内容全都展示,右表只展示与左表相关内容
--使用左外连接查询员工id,姓名,工资,部门编号,部门名
select e.employee_id,e.first_name,e.salary,e.department_id,d.department_name
from employees e left outer join departments d
on e.department_id = d.department_id
-
右外连接
关键字:right join
语法规则:>from 表1 right [outer] join 表2 on 表1.字段名 = 表2.字段名
-
全外连接
关键字:full join
语法规则:>from 表1 full [outer] join 表2 on 表1.字段名 = 表2.字段名
3.表连接的应用
--需求:查询部门信息:部门编号,部门名称,部门所在地标号,部门所在城市
--表连接 departments lcoations 链接条件 d.location_id = l.location_id
select * from departments d left join locations l on d.location_id = l.location_id
--需求:查询员工的工号,名字,工资,部门编号,部门名称,部门所在地编号,部门所在城市
-- 表连接 employees departments lcoations
--1.链接 employees departments
select * from employees e left join departments d on e.department_id = d.department_id
--2.将上述结果与locations链接
select * from employees e left join departments d on e.department_id = d.department_id left join locations l on d.location_id = l.location_id
--需求:查询员工的工号,名字,工资,领导编号,领导名字
--表连接 员工表(employees) 领导表(employees) 自连接
--物理上是同一张表,逻辑上是两张表
select e1.*,e2.* from employees e1 left join employees e2 on e1.manager_id = e2.employee_id