一、子查询
出现在其他语句中的select语句,称为子查询或内查询
外部的查询语句,称为主查询或外查
分类:
按子查询出现的位置:
select后面:仅仅支持标量子查询
from后面:支持表子查询
where或having后面«:支持标量子查询,列子查询,行子查询
exists后面(相关子查询):支持标量子查询、列子查询、行子查询、表子查询
按结果集的行列数不同:
标量子查询(单行子查询,结果集只有一行一列)
列子查询(多行子查询,结果集只有一列多行)
行子查询(结果集有一行多列)
表子查询(结果集一般为多行多列)
特点:
①子查询放在小括号内
②子查询一般放在条件的右侧
③标量子查询,一般搭配着单行操作符使用 > ,<, >=, <=, =, <>
列子查询,一般搭配着多行操作符使用 in/not in 等于列表中的任意一个 , any / some 和子查询返回的某一个值比较 , all 和子查询返回的所有值比较
④子查询的执行优先于主查询执行,主查询的条件用到了子查询的结果
(1)where或having之后
标量子查询
例:查询最低工资大于50号部门最低工资的部门id和其最低工资
select min(salary), department_id
from employees
group by department_id
having min(salary)>(
select min(salary)
from employees
where department_id = 50
)
列子查询
例:返回其他部门中比job_id为’IT_PROG’部门所有工资都低的员工的员工号、姓名、job_id以及salary。
select last_name, employee_id, job_id, salary
from employees
where salary<all(
select distinct salary
from employees
where job_id=’IT_PROG’
) and job_id<>’IT_PROG’;
行子查询
例:查询员工编号最小并且工资最高的员工信息
select *
from employees
where (employee_id, salary) = (
select min(employee_id), max(salary)
from employees
);
(2)select后面
例:查询员工号为102的部门号
select (
select department_name
from departments d
inner join employees e
on d.department_id = e.department_id
where e.employee_id=102
) 部门名;
(3)from后面
特点:将子查询的结果放在from后面,要求必须起别名
例:查询每个部门的平均工资的工资等级
select ag_dep.* , g.’grade_level’
from (
select avg(salary) ag, department_id
from employees
group by department_id
) ag_dep
inner join job_grades g
on ag_dep.ag between lowest_sal and highest_sal;
(4)exists后面(相关子查询)
语法:
exists(完整的查询语句)
结果:1或0
例:查询有员工的部门名
select department_name
from departments d
where exists(
select *
from employees e
where d.’department_id’ = e.’department_id’
);
二、分页查询
应用场景:当要显示的数据,一页显示不全,需要分页提交sql请求
语法:
select 查询列表
from 表
【join type join 表2
on 连接条件;
where 筛选条件
group by 分组字段
having 分组后的筛选
order by 排序的字段】
limit offset , size;
》offset 要显示条目的起始索引(起始索引从0开始)
》size 要显示的条目个数
特点:
①limit语句放在查询语句的最后
②公式
要显示的页数 page, 每页的条目数size
select 查询列表
from 表
limit (page-1)*size, size;
例:查询前五条员工信息
select * from employees limit 0,5;
三、联合查询
union 联合 合并:将多条查询语句的结果合并成一个结果
语法:
查询语句1
union 【all】
查询语句2
union 【all】
...
应用场景:
要查询的结果来自于多个表,且多个表没有直接的连接关系,但查询的信息一致时。
特点:
- 要求多条查询语句的查询列数是一致的;
- 要求多条查询语句的查询的每一列的类型和顺序最好一致
- Union关键字默认去重,如果使用union all可以包含重复项