分类:
按子查询出现的位置:
select后面:
标量子查询
where或having:
标量
列子查询
行子查询
exists
表子查询
按结果的行列数不同:
标量子查询(结果一行一列)
列子查询(结果集一行多列)
行子查询(结果集一列多行)
表子查询(结果集多行多列)
一.where或者having后面
1.标量子查询
2.列子查询
3.行子查询
特点:
①子查询放在小括号里
②子查询一般放在条件的右侧
③标量子查询,一般搭配着单行操作符使用
> < >= <= = <>
④列子查询一般搭配多行操作符使用
in any/some all
1.标量子查询
例子:
查询比able工资高的信息;
select *
from employees
where salary>(
select salary
from employees
where last_name = \`able`
);
2.列子查询
例子:
返回location_id是1400或1700的部门中的所有员工姓名
1.查询location_id是1400或1700的部门编号
select department_id
from departments
where location_id IN(1400,1700);
2.查询员工姓名,要求部门编号是1列表中的某一个
select last_name
from employess
where department_id IN(
select department_id
from departments
where location_id IN(1400,1700);
);
三.行子查询
例子:
查询员工编号最小并且工资最高的人
select * from
from (employee_id,salary)=(
select min(employee_id),max(salary)
from employees
) ; //employee_id=min(employee_id),salary=max(salary)
四.exists
语法:
exists(完整的查询语句)
结果:
1或者0