MySQL(04)—常见函数

子查询

概念:出现在其他语句内部的select语句,称为子 查询或内查询;内部嵌套其他select语句的查询,称为外查询或主 查询
示例:

1
2
3
4
5
6
7
8
select first_name 
from employees
where department_id in(
select department_id
from departments
where location_id=1700
)

注意事项

  • 子查询要包含在括号内

  • 将子查询放在比较条件的右侧

  • 单行操作符对象单行子查询,多行操作符对应多行子查询

  • 单行子查询

    image-20210819092714187

  • 多行子查询

    image-20210819092801406

1. 单行子查询

只返回一行,使用单行比较操作符

操作符 含义
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to

子查询语法

1
2
3
4
5
6
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);

子查询 (内查询) 在主查询之前一次执行完成。 子查询的结果被主查询(外查询)使用 。

使用子查询解决问题

谁的工资比Abel高?

image-20210819093644144

1
2
3
4
5
SELECT last_name
FROM employees
WHERE salary >(SELECT salary
FROM employees
WHERE last_name = 'Abel');
image-20210819094032607
  1. 执行单行子查询

    返回job_id与141号员工相同,salary比143号员工多的员工的姓名,job_id和工资

    1
    2
    3
    4
    5
    6
    7
    8
    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);
    image-20210819095441015
  2. 在子查询中使用组函数

    返回公司工资最少的员工的last_name,job_id和salary

    1
    2
    3
    4
    5
    select last_name,job_id,salary
    from employees
    where salary = (select min(salary)
    from employees
    );
    image-20210819101029244
  3. 子查询中的HAVING子句

    首先执行子查询,向主查询中的HAVING子句返回结果

    查询最低工资大于50号部门最低工资的部门id和其最低工资

    1
    2
    3
    4
    5
    6
    select department_id,min(salary)
    from employees
    group by department_id
    having min(salary) > (select min(salary)
    from employees
    where department_id = 50);
    image-20210819105231528

2. 多行子查询

返回多行,使用多行比较操作符

操作符 含义
IN/NOT IN 等于列表中的任意一个
ANY | SOME 和子查询返回的某一个值比较
ALL 和子查询返回的所有值比较

体会any和all的区别

  1. 使用IN操作符

    返回location_id是1400或1700的部门中的所有员工姓名

    1
    2
    3
    select last_name
    from employeesleft join locations
    on location_id in (1400,1700);
    image-20210819124909755
  2. 在多行子查询中使用ANY操作符

    返回其他部门中比job_id为’IT_PROG’部门任意某一工资低的员工的员工号、姓名、job_id以及salary

    1
    2
    3
    4
    5
    6
    select 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';

    image-20210819125713691

  3. 在多行子查询中使用ALL操作符

    返回其它部门中比job_id为‘IT_PROG’部门所有工资都低的员工 的员工号、姓名、job_id 以及salary

    1
    2
    3
    4
    5
    6
    select 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';

    image-20210819130023721