目录
1.数据库来源:Mysql 基础教程
2.数据库说明:
本文使用的第一个数据库名称为 myemployees,其中有 8 张表,分别为 customers 表,departments 表,employees 表,job_grades 表,jobs 表,locations 表,orders 表,salespeople 表。
一、SQL99 连接查询基本语法
select 查询列表
from 表1 别名 【连接类型】
join 表2 别名
on 连接条件
where 筛选条件1
group by 分组
having 筛选条件2
order by 排序列表
二、SQL99 内连接分类及相关案例(仅展示有限部分)
2.1 内连接语法
select 查询列表
from 表1 别名
join 表2 别名
on 连接条件
2.2 内连接特点
1、添加排序、分组、筛选
2、inner 可以省略
3、筛选条件放在where后面,连接条件放在on后面,提高分离性,便于阅读
2.3 内连接分类及相关案例
2.3.1 等值连接
案例一:查询名字中包含 e 的员工名和工种名
select last_name, job_title
from employees e
join jobs j
on e.job_id = j.job_id
案例二:查询部门个数 >3 的城市名和部门个数
select city, count(*) as 部门个数
from locations l
join departments d
on l.location_id = d.location_id
group by city
having count(*) > 3
案例三:查询哪个部门的员工个数 >3 的部门名和员工个数,并按个数降序
select department_name, count(*) as 员工个数
from departments d
join employees e
on d.department_id = e.department_id
group by department_name
having count(*) > 3
order by count(*) desc
2.3.2 非等值连接
案例一:查询员工的工资级别
select last_name, salary, grade_level
from employees e
join job_grades g
on e.salary between g.lowest_sal and g.highest_sal
案例二:查询工资级别个数 >10 的,并按工资级别降序
select grade_level, count(*) 个数
from employees e
join job_grades g
on e.salary between g.lowest_sal and g.highest_sal
group by grade_level
having count(*) > 10
order by grade_level desc
2.3.3 自连接
案例一:查询姓名中包含字符 k 的员工的名字及其上级的名字
select e.last_name as 员工姓名, m.last_name as 上级姓名
from employees e
join employees m
on e.manager_id = m.employee_id
where e.last_name like '%k%'
三、SQL99 外连接分类及相关案例(仅展示有限部分)
3.1 外连接语法
select 查询列表
from 表1 别名
left join/right join/outer join 表2 别名
on 连接条件
3.2 外连接特点
1、外连接的查询结果为主表中的所有记录
① 如果从表中有和它匹配的,则显示匹配的值
② 如果从表中没有和它匹配的,则显示null
③ 外连接查询结果 =内连接结果 + 主表中有而从表没有的记录
2、左外连接,left join 左边的是主表。右外连接,right join右边的是主表
3、左外和右外交换两个表的顺序,可以实现同样的效果
3.3 外连接分类及相关案例
3.3.1 左外连接
案例一:查询哪个部门没有员工
select d.department_id, d.department_name
from departments d
left join employees e
on d.department_id = e.department_id
where e.employee_id is null
3.3.2 右外连接
select d.department_id, d.department_name
from employees e
right join departments d
on e.department_id = d.department_id
where e.employee_id is null