# 案例:查询有奖金的员工的员工名、部门名、城市
SELECT `last_name`, `department_name`, `city`
FROM `locations` lo, `employees` e, `departments` d
WHERE
e.`commission_pct` IS NOT NULL AND
e.`department_id` = d.`department_id` AND
d.`location_id` = lo.`location_id`;
SQL99的语法
# 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%';
# 2、内连接 ------ 非等值连接
# 案例:查询员工的工资级别
SELECT `grade_level`, `salary`
FROM `employees` e
INNER JOIN `job_grades` g
ON e.`salary` BETWEEN g.`lowest_sal` AND g.`highest_sal`
# 3、内连接 ------ 自连接
# 案例:查询员工姓名、领导姓名
SELECT e.`last_name`, m.`last_name`
FROM `employees` e
INNER JOIN `employees` m
ON e.`manager_id` = m.`employee_id`
# 4. 外连接
# 案例1:查询男朋友不在男神表的 女生姓名:女神是主表,拿 主表的参数 去 匹配副表
SELECT b.`name`
FROM `beauty` b
LEFT JOIN `boys` bo
ON b.`boyfriend_id` = bo.`id`
WHERE bo.`id` IS NULL;
# 案例2:查询没有部门的城市
SELECT lo.`city`
FROM `locations` lo
LEFT JOIN `departments` d
ON d.`location_id` = lo.`location_id`
WHERE `department_id` IS NOT NULL;
# 案例3:查询没有员工的部门
# 左外
SELECT d.*
FROM departments d
LEFT JOIN employees e
ON d.department_id = e.department_id
WHERE e.email IS NULL
# 右外
SELECT d.*
FROM employees e
RIGHT JOIN departments d
ON e.department_id = d.department_id
WHERE e.email IS NULL;
# 案例4:查询部门名为SAL或IT的员工信息
SELECT e.*
FROM `employees` e
LEFT JOIN `departments` d
ON e.`department_id` = d.`department_id`
WHERE d.`department_name` IN('SAL', 'IT')