含义:出现在其他语句中的select语句,称为子查询或内查询
外部的查询语句,称为主查询或外查询
分类:
按子查询出现的位置:
- select后面(仅仅支持标量子查询)
- from后面(支持表子查询)
- where或having后面(标量子查询、列子查询 单行、行子查询 多行)
- exists后面(相关子查询,表子查询)
按结果集的行列数不同
- 标量子查询(结果集只有一行一列)
- 列子查询(结果集只有一列多行)
- 行子查询(结果集有一行多列)
重点:where或having后面
特点:
- 子查询放在小括号内
- 子查询一般放在条件的右侧
- 标量子查询,一般搭配着单行操作符使用> < >= <= <> 列子查询,一般搭配着多行操作符使用inany/some、all
- 子查询的执行优先于主查询执行,主查询的条件用到了子查询的结果
一、where或having后面
案例1:谁的工资比Abel高
1、查询Abel的工资
SELECT salary
FROM employees
WHERE last_name = 'Abel';
2、查询员工的信息,满足salary>1的结果
SELECT *
FROM employees
WHERE salary>(
SELECT salary
FROM employees
WHERE last_name = 'Able'
);
案例2:返回job_id与141号员工相同,salary比143号员工多的员工 姓名,job_id和工资
1、查询141号员工的job_id
SELECT job_id
FROM employees
WHERE employee_id = 141
2、查询143号员工的salary
SELECT salary
FROM employees
WHERE employee_id=143
3、查询员工的姓名,job_id和工资,要求job_id=1、并且salary>2、
SELECT last_name,job_id,salary
FROM employees
WHERE job_id = (
SELECT job_id
FROM employees
WHERE employee_id = 141
) AND salary>(
SELECT salary
FROM employees
WHERE employee_id=143
)
案例3:返回公司中工资最少的员工的last_name,job_id和salary
SELECT MIN(salary),department_id
FROM employees
GROUP BY department_id
HAVING MIN(salary)>(
SELECT MIN(salary)
FROM employees
WHERE department_id = 50
)
非法使用标量子查询:子查询的结果不是一行一列
多列子查询
操作符 | 含义 |
IN/NOT IN | 等于列表中的任意一个 |
ANY|SOME | 和子查询返回的某一个值比较 |
ALL | 和子查询返回的所有值比较 |
案例:返回location_id是1400或1700的部门中的所有员工姓名、
SELECT last_name
FROM employees
WHERE department_id IN(
SELECT DISTINCT department_id
FROM departments
WHERE location_id IN(1400,1700)
);
行子查询(结果集一行多列或多行多列)
案例:查询员工编号最小并且工资最高的员工信息
SELECT *
FROM employees
WHERE (employee_id,salary)=(
SELECT MIN(employee_id),MAX(salary)
FROM employees
)
二、select后面
案例1:查询每个部门的员工个数
SELECT d.*,(
SELECT COUNT(*)
FROM employees e
WHERE e.department_id = d.`department_id`
)个数
FROM departments d;
案例2:查询员工号=102的部门名
SELECT (
SELECT department_name
FROM departments d
INNER JOIN employees e
ON d.department_id=e.department_id
WHERE e.employee_id=102
)部门名;
三、from后面
案例:查询每个部门的平均工资的工资等级
1、查询每个部门的平均工资
SELECT AVG(salary),department_id
FROM employees
GROUP BY department_id
2、连接1、的结果集和job_grades表,筛选条件平均工资between lowest_sal and highest_sal
SELECT ag_dep.*,g.grade_level
FROM(
SELECT AVG(salary),department_id
FROM employees
GROUP BY department_id
)ag_dep
INNER JOIN job_grades g
ON ag_dep.ag BETWEEN lowest_sal AND high_sal
四、exists后面(相关子查询)
语法:exists(完整的查询语句)
结果:1或0
案例1:查询有员工名的部门名
SELECT department_name
FROM departments d
WHERE EXISTS(
SELECT *
FROM employees e
WHERE d.`department_id`=e.`department_id`
);