含义:出现在其他语句中的select语句,称为子查询或内查询
外部的查询语句,称为主查询或外查询
分类:
- 按子查询出现的位置:
select后面:仅仅支持标量子查询
from后面:支持表子查询
(※)where或having后面:标量子查询(单行)、列子查询(多行)、行子查询
exists后面(相关子查询):支持表子查询
按结果集的行列数不同:
标量子查询(结果集只有一行一列)<br /> 列子查询/多行子查询(结果集只有一列多行)<br /> 行子查询(结果集有一行多列)<br /> 表子查询(一般为多行多列)
一、出现在where或者having后面
特点:
①子查询放在小括号内
②子查询一般放在条件的右侧
③标量子查询,一般搭配着单行操作符(> < >= <= = <>)使用
④列子查询,一般搭配着多行操作符使用(in、any/some、all)
1、标量子查询(单行子查询)
案例一:谁的工资比Abel高?
#1、首先查询Abel的工资select salaryfrom employeeswhere last_name='Abel';#2、查询员工的信息,满足salary>1的结果select *from employeeswhere salary>(select salaryfrom employeeswhere last_name='Abel');
案例二:返回job_id与141号员工相同,salary比143号员工多的员工的姓名,job_id和工资
#1、查询141号员工的job_idselect job_idfrom employeeswhere employee_id=141#2、查询143号员工的salaryselect salaryfrom employeeswhere employee_id=143#3、查询员工的姓名,job_id和工资,要求job_id=1并且salary>2select last_name,job_id,salaryfrom employeeswhere job_id=(select job_idfrom employeeswhere employee_id=141)and salary>(select salaryfrom employeeswhere employee_id=143);
案例三:返回公司工资最少的员工的last_name,job_id和salary
#1、先查询公司的最低工资select min(salary)from employees#2、查询last_name,job_id,salary,要求salary=1select last_name,job_id,salaryfrom employeeswhere salary=(select min(salary)from employees);
案例四:查询最低工资大于50号部门最低工资的部门id和其最低工资
#1、查询50号部门的最低工资select min(salary)from employeeswhere department_id=50#2、查询每个部门的最低工资select min(salary)from employeesgroup by department_id#3、筛选2,满足min(salary)>1的结果select min(salary),department_idfrom employeesgroup by department_idhaving min(salary)>(select min(salary)from employeeswhere department_id=50);
