MySQL(04)—常见函数
子查询
概念:出现在其他语句内部的select语句,称为子 查询或内查询;内部嵌套其他select语句的查询,称为外查询或主 查询
示例:
1 | select first_name |
注意事项
子查询要包含在括号内
将子查询放在比较条件的右侧
单行操作符对象单行子查询,多行操作符对应多行子查询
单行子查询

多行子查询

1. 单行子查询
只返回一行,使用单行比较操作符
| 操作符 | 含义 |
|---|---|
| = | Equal to |
| > | Greater than |
| >= | Greater than or equal to |
| < | Less than |
| <= | Less than or equal to |
| <> | Not equal to |
子查询语法
1 | SELECT select_list |
子查询 (内查询) 在主查询之前一次执行完成。 子查询的结果被主查询(外查询)使用 。
使用子查询解决问题
谁的工资比Abel高?

1 | SELECT last_name |
执行单行子查询
返回job_id与141号员工相同,salary比143号员工多的员工的姓名,job_id和工资
1
2
3
4
5
6
7
8select 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);
在子查询中使用组函数
返回公司工资最少的员工的last_name,job_id和salary
1
2
3
4
5select last_name,job_id,salary
from employees
where salary = (select min(salary)
from employees
);
子查询中的HAVING子句
首先执行子查询,向主查询中的HAVING子句返回结果
查询最低工资大于50号部门最低工资的部门id和其最低工资
1
2
3
4
5
6select department_id,min(salary)
from employees
group by department_id
having min(salary) > (select min(salary)
from employees
where department_id = 50);
2. 多行子查询
返回多行,使用多行比较操作符
| 操作符 | 含义 |
|---|---|
| IN/NOT IN | 等于列表中的任意一个 |
| ANY | SOME | 和子查询返回的某一个值比较 |
| ALL | 和子查询返回的所有值比较 |
体会any和all的区别
使用IN操作符
返回location_id是1400或1700的部门中的所有员工姓名
1
2
3select last_name
from employeesleft join locations
on location_id in (1400,1700);
在多行子查询中使用ANY操作符
返回其他部门中比job_id为’IT_PROG’部门任意某一工资低的员工的员工号、姓名、job_id以及salary
1
2
3
4
5
6select employee_id,last_name,job_id,salary
from employees
where salary < any(select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG';
在多行子查询中使用ALL操作符
返回其它部门中比job_id为‘IT_PROG’部门所有工资都低的员工 的员工号、姓名、job_id 以及salary
1
2
3
4
5
6select employee_id,last_name,job_id,salary
from employees
where salary < all(select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG';