二、sql99语法
语法:
select 查询列表
from 表1 别名 【连接类型】
join 表2 别名
on 连接条件
【where筛选条件】
【group by 分组】
【having 筛选条件】
【order by 排序列表】
分类:
内连接(☆):inner
外连接:
左外(☆):left(outer)
右外(☆):right(outer)
全外:full(outer)
交叉连接:cross
一、内连接
select 查询列表
from 表1 别名
inner join 表2 别名
on 连接条件;
分类:
等值
非等值
自连接
特点:
①添加排序、分组、筛选
②inner可以省略
③筛选条件放在where后面,连接条件放在on后面,提高分离性,便于阅读
④inner join连接与sql92语法中的等值连接效果是一样的,都是查询多表的交集部分
1.等值连接
案例1:查询员工名、部门名
SELECT last_name ,department_name
from employees e
inner join departments d
on e.department_id = d.department_id
案例2:查询名字中包含e的员工名和工种名(添加筛选)
select last_name,job_title
from employees e
inner join jobs j
on e.job_id = j.job_id
where e.last_name like '%e%';
案例3:查询部门个数>3的城市名和部门个数(添加分组+筛选)
①查询每个城市的部门个数
②在①结果上筛选满足条件的
SELECT city ,count(*) 部门个数
from departments d
inner join locations l
on d.location_id = l.location_id
group by city
having count(*)>3
案例4:查询哪个部门的部门员工个数>3的部门名和员工个数,并按个数降序(排序)
①查询每个部门的员工个数
select count(*),department_name
from employees e
inner join departments d
on e.department_id = d.department_id
group by department_name
②在①的结果上筛选员工个数>3的记录并排序
select count(*),department_name
from employees e
inner join departments d
on e.department_id = d.department_id
group by department_name
having count(*)>3
order by count(*) desc
案例5:查询员工名、部门名、工种名,并按部门名降序
select last_name ,department_name,job_title
from employees e
inner join departments d
on e.department_id = d.department_id
inner join jobs j
on e.job_id = j.job_id
order by department_name desc
2.非等值连接
查询员工的工资级别
select salary ,grade_level
from employees e
inner join job_grades g
on e.salary BETWEEN g.lowest_sal AND g.highest_sal
查询工资级别>20的个数,并且按工资级别降序
select count(*) ,grade_level
from employees e
inner join job_grades g
on e.salary BETWEEN g.lowest_sal AND g.highest_sal
group by grade_level
having count(*)>20
order by grade_level desc
3.自连接
查询员工的名字、上级的名字
select e.last_name,m.last_name
from employees e
inner join employees m
on e.manager_id = m.employee_id
二、外连接
应用场景:用于查询一个表中有,另一个表中没有的记录
特点:
1.外连接的查询结果为主表中的所有记录
如果从表中有和它匹配的,则显示匹配的值
如果从表中没有和它匹配的,则显示null
外连接查询结果=内连接结果+主表中从来没有的记录
2.左外连接,left join左边的是主表
右外连接,right join右边的是主表
3.左外和右外交换两个表的顺序,可以实现同样的效果
右外连接
select b.name,bo.*
from boys bo
right join beauty b
on b.boyfriend_id = bo.id
where bo.id is null
案例1:查询哪个部门没有员工
左外连接
select d.*,employee_id
from departments d
left outer join employees e
on d.department_id = e.department_id
where employee_id is null