【MySQL】相关子查询(关联子查询)
1.相关子查询
示例1:查询员工中工资大于本部门平均工资的员工的last_name,salary和其department_id。
在子查询中使用到了外部的表,并进行条件关联,每执行一次外部查询,子查询都要重新计算一次。
2.在from中使用子查询
必须要给from中的子查询起别名,当成一张临时表
SELECT last_name,salary,a.department_id
FROM employees a,(SELECT department_id,AVG(salary) AS dept_avg_sal FROM employees GROUP BY department_id) b
WHERE a.department_id = b.department_id
AND a.salary>b.dept_avg_sal;
3.Order by中使用子查询
示例1:查询员工的id,salary,按照department_name 排序
SELECT employee_id,salary,department_id
FROM employees a
ORDER BY (
SELECT department_name
FROM departments b
WHERE a.department_id = b.department_id
);
示例2:若employees表中employee_id与job_history表中employee_id相同的数目不小于2,输出这些相同id的员工的employee_id,last_name和其job_id
SELECT a.employee_id,a.last_name,a.job_id
FROM employees a
WHERE 2<=(
SELECT COUNT(*)
FROM job_history
WHERE employee_id = a.employee_id
);
4.EXISTS与NOT EXISTS关键字
EXISTS使用
- 如果在子查询中不存在满足条件的行
- 条件返回false
- 继续在子查询中查找
- 如果在子查询中存在满足条件的行
- 条件返回true
- 不在子查询中继续查找
NOT EXISTS则相反
示例1:查询公司管理者的employee_id,last_name,job_id,department_id信息
方式一:
SELECT employee_id,last_name,job_id,department_id
FROM employees a
WHERE EXISTS (
SELECT *
FROM employees b
WHERE a.employee_id = b.manager_id
);
方式二:
SELECT DISTINCT a.employee_id,a.last_name,a.job_id,a.department_id
FROM employees a
JOIN employees b ON a.employee_id = b.manager_id;
方式三:
SELECT employee_id,last_name,job_id,department_id
FROM employees
WHERE employee_id IN(
SELECT DISTINCT manager_id
FROM employees
);
示例2:查询departments表中,不存在于employees表中的部门的department_id和department_name
SELECT department_id,department_name
FROM departments a
WHERE NOT EXISTS(
SELECT 'X'
FROM employees
WHERE department_id = a.department_id
);
5.相关更新
使用相关子查询依据一个表中的数据更新另一个表的数据。
在employees中增加一个department_name字段,数据为员工对应的部门名称。
#添加字段
ALTER TABLE employees
ADD(department_name VARCHAR(14));
#更新数据
UPDATE employees a
SET departments_name = (
SELECT department_name
FROM departments b
WHERE a.department_id = b.department_id
);
6.相关删除
使用相关子查询依据一个表中的数据删除另一个表的数据
示例:删除表employees中,其与emp_history表皆有的数据。
DELETE FROM employees a
WHERE employee_id IN (
SELECT employee_id
FROM emp_history
WHERE employee_id = a.employee_id
);
7.自连接和子查询比较
示例:谁的工资比Abel的高?
方式一:自连接
SELECT b.last_name,b.salary
FROM employees a,employees b
WHERE a.last_name = 'Abel'
AND a.salary < b.salary;
方式二:子查询
SELECT last_name,salary
FROM employees
WHERE salary > (
SELECT salary
FROM employees
WHERE last_name = 'Abel'
);
一般建议使用自连接,因为许多的DBMS处理过程中,对于自连接的处理速度要比子查询快得多。
理解:子查询实际上是通过位置表进行查询后的条件判断,而自连接是通过已知的自身数据表进行条件判断。