连接查询
连接查询
sql92语法,where
等值连接
// 基本写法
select 字段1,字段2
from 表1,表2
where 表1.id = 表.id
// 为表起别名
select 字段1,字段2
from 表1 as aaa,表2 as bbb
where aaa.id = bbb.id
// 加筛选
select 字段1,字段2
from 表1 as aaa,表2 as bbb
where aaa.id = bbb.id
and 字段1="ok"
// 加分组
select 字段1,字段2
from 表1 as aaa,表2 as bbb
where aaa.id = bbb.id
and 字段1="ok"
group by 字段2
// 加排序
非等值连接
自连接
把自身的一张表当作多个表使用
查询员工名和上级的名称
select a.'employee_id',a.'last_name',b.'employee_id',b.'last_name'
from employees a,employees b
where a.'manager.id' = b.'employee_id'
sql99语法,join
内连接,外连接,交叉连接
内连接
select 查询列表
from 表1 别名
inner join 表2 别名
on 连接条件【等值,非等值,自连接】
内连接的等值连接
查询员工名(last_name),部门名(department_name)
select last_name,department_name
from employees 员工表
inner join departments 部门表
on 员工表.'department_id' = 部门表.'department_id'
内连接的非等值连接
查询员工的工资级别
select salary,grade_leavel
from employees 员工表
join job_grades 工资等级表
on 员工表.salary between 工资等级表.'lowest_sal' and 工资等级表.'hightest_sal'
外连接
相对于一个做主表一个做从表,用于查询一个表有,另一个表没有的记录
就是外连接查询的结果为主表中的所有记录,
如果从表中有和它匹配的,则显示匹配的值,
如果从表中没有和它匹配的,则显示null
外连接查询结果 = 内连接结果 + 主表中有的数据而从表中没有的数据
左外连接
left join 左边的是主表
select 主表.*,主表.*
from 主表
left outer join 从表
on 主表.uID = 从表.uID
案例 : 查询哪个部门没有员工
部门表 department
部门ID department_id
员工表 employee
员工ID employee_id
select main.*,
from department main
left outer join employee other
on main.department_id = other.department_id
where other.employee_id is null
右外连接
right join 右边的是主表
select 主表.*,主表.*
from 主表
right outer join 从表
on 主表.uID = 从表.uID
全外连接
全外连接 = 内连接结果 + 表1中有但表2中没有 + 表1中没有但表2中有
select 表1.*,表2.*
from 表1
full outer join 表2
on 表1.uID = 表2.uID
交叉连接
笛卡尔乘积,使用99语法标准
select 表1.*,表2.*
from 表1
cross outer join 表2
小结
何时使用内连接
何时使用左外连接
A当主表