连接查询按照功能分类
内连接
等值连接
非等值连接
自连接 //92SQL
外连接: //红色的连接查询类型92版SQL
左外连接
右外连接
全外连接
交叉连接
#剩下连接类型的SQL语法就不是前面同一个发布版本了
99版SQL语法格式区别于92版的是连接不在是用"="了,它是语法格式:
sql
select 查询列表
from 表1 别名
【链接类型】 join 表2 别名
on 链接条件
where 数据筛选条件 .....以前讲过的其他部分;
【链接类型】的关键字
内连接:inner (还可以省略)
外连接:
左外连接 left 【outer】
右外连接 right 【outer】
全外连接 full 【outer】
交叉连接 cross 【outer】
案例1:用99版的SQL写法实现等值连接查询
1.查询员工名和其对应所属的部门名
sql
select last_name,department_name
from employees e
inner join departments d
on e.department_id = d.department_id;
2.查询名字中包含e字母的员工名和其对象的部门名
sql
select last_name , department_name
from employees e
inner join departments d
on e.department_id = d.department_id
where last_name like '%e%';
3.查询所在部门个数大于3的城市名和部门个数
sql
select count(d.department_id) count , l.city
from departments d
inner join locations l
on d.location_id = l.location_id
group by l.city
having count>3;
4.查询员工个数大于3点部门名和员工个数,降序排序
sql
SELECT d.department_name , COUNT(e.employee_id) c
FROM employees e
INNER JOIN departments d
ON e.department_id=d.department_id
GROUP BY d.department_name
HAVING c>3
ORDER BY c DESC;
5.查询员工名以及对应的工种名和部门名,按部门名降序排序
sql
select e.last_name,j.job_title,d.department_name
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 d.department_name;
案例2:用99版的SQL写法实现非等值连接查询
sql
SELECT
salary,grade_level
FROM
employees e
INNER JOIN
job_grades g
ON
e.salary BETWEEN g.`lowest_sal` AND g.`highest_sal`;
练习
查询同一个工资级别的员工的个数大于20的员工个数,并且按照工资级别降序排序
sql
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:用99版的SQL写法实现自连接查询
查询员工的名和其对应的直属领导
sql
SELECT
e.last_name employee_name,
m.last_name manager_name
FROM
employees e
INNER JOIN
employees m
ON
e.`manager_id`=m.`employee_id`;