# 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 join 表3 别名 on 连接条件
【where 筛选条件】
【group by 分组】
【having 分组后筛选】
【order by 排序列表】
分类:等值,非等值,自连接
*/
#1 等值连接
#案例1:查询员工名,部门名 【等值内连】
SELECT last_name,department_name
FROM employees AS e
INNER JOIN departments AS d
ON e.`department_id` = d.`department_id`;
#案例2:查询名字中包含e的员工名和工种名【等值内连 + 筛选】
SELECT last_name, job_title
FROM employees AS e
INNER JOIN jobs AS j
ON e.`job_id` = j.`job_id`
WHERE last_name LIKE ‘%e%‘;
#案例3:查询部门个数>3的城市名和部门个数【等值内连+分组+分组后筛选】
SELECT city,COUNT(*) AS "部门个数"
FROM departments AS d
INNER JOIN locations AS l
ON d.`location_id` = l.`location_id`
GROUP BY l.`city`
HAVING 部门个数>3;
#案例4:查询部门员工数>3的部门名称和员工个数,并降序排序
#【等值连接+分组+分组后筛选+ 排序】
SELECT department_name, COUNT(*) AS "员工个数"
FROM departments AS d
INNER JOIN employees AS e
ON d.`department_id` = e.`department_id`
GROUP BY e.`department_id`
HAVING 员工个数 > 3
ORDER BY 员工个数 DESC;
#案例5:查询员工名,部门名,工种名,并按部门名排序
#【多表等值连接+排序】
SELECT last_name, department_name, job_title
FROM employees AS e
INNER JOIN departments d ON e.`department_id` = d.`department_id`
INNER JOIN jobs AS j ON e.`job_id` = j.`job_id`
ORDER BY department_name DESC;
#2 非等值连接
#案例1:查询员工的工资级别
SELECT salary,grade_level
FROM employees AS e
INNER JOIN job_grades AS j
ON e.salary BETWEEN j.`lowest_sal` AND j.`highest_sal`;
#案例2:查询每个工资级别下员工个数》2的工资级别,并降序排列
SELECT COUNT(*), grade_level
FROM employees AS e
INNER JOIN job_grades AS j
ON e.`salary` BETWEEN j.`lowest_sal` AND j.`highest_sal`
GROUP BY grade_level
HAVING COUNT(*) > 20
ORDER BY COUNT(*) DESC;
#3 内连接中的自连接
#案例1:查询员工的名字,及其上级的名字
SELECT e.last_name, m.last_name
FROM employees AS e
INNER JOIN employees AS m
ON e.`manager_id` = m.`employee_id`
ORDER BY e.`last_name` ASC;
#案例2:查询名字中包含字符k的员工名,及其上级的名字
SELECT e.last_name, m.last_name
FROM employees AS e
INNER JOIN employees AS m
ON e.`manager_id` = m.`employee_id`
WHERE e.`last_name` LIKE ‘%k%‘
ORDER BY e.`last_name` ASC;