• 含义:
    出现在其他语句中的select语句,称为子查询或内查询,外部的查询语句,称为主查询或外查询。
  • 分类:
    按子查询出现的位置:

    select 后面:    仅仅支持标量子查询from 后面    支持表子查询where或having后面    标量子查询    列子查询    行子查询exists后面(相关子查询)    表子查询

    按结果集的行列数不同:

    标量子查询(结果集只有一行一列)列子查询(结果集有一列多行)行子查询(结果集有一行多列)表子查询(结果集一般为多行多列)

一、where或having后面

特点:

子查询放在小括号内子查询一般放在条件的右侧标量子查询,一般搭配单行操作符使用> < >= <= = <>列子查询,一般搭配着多行操作符使用IN、ANY/SOME、ALL

标量子查询

  1. 查询谁的工资比Abel高

    select salary from employees where last_name='Abel' // 一行一列 11000select last_name,salary from employees where salary > (select salary from employees where last_name='Abel')
  2. 查询最低工资大于50号部门最低工资的部门id和其最低工资

    #查询50号部门最低工资select min(salary) from employees where department_id=50 // 2100#按条件查询select department_id,min(salary) from employees GROUP BY department_id HAVING min(salary)> (select min(salary) from employees where department_id=50)

列子查询

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

    #查询所有部门idselect department_id from departments where location_id=1400 or location_id=1700

    #查询员工姓名是上面查询部门中的某一个select last_name from employees where department_id in (select department_id from departments where location_id=1400 or location_id=1700)

列子查询

  1. 查询员工编号最小,并且工资最高的员工信息

    select * from employees where (employee_id, salary) = (select min(employee_id), max(salary) from employees)

一、select 后面

标量子查询

  1. 查询每个部门员工个数

    select *, (select count(*) from employees e where e.department_id = d.department_id)  from departments d

一、from后面

表子查询

  1. 查询每个部门的平均工资的工资等级
SELECT ag_dep.*, g.grade_level FROM (SELECT avg(salary) as ag, department_id FROM employees GROUP BY department_id) ag_depJOIN job_grades g ON ag_dep.ag BETWEEN lowest_sal AND highest_sal

一、exists后面(相关子查询)

语法:

exists(完整的查询语句)结果:1或0
  1. 查询每个部门员工个数
select department_name from departments d where EXISTS (select * from employees e where e.department_id = d.department_id)

子查询中select 后面可以用employees表中的任何字段或*