业务的不断发展,表与表之间的关系不断复杂,查询语句也会变得越来越复杂,在查询结果中过滤自己想要的数据也越来越常见。也就出现了在查询中查询的结果。
子查询
在查询中查询,也叫嵌套查询。按照返回结果分为三类:
- 标量子查询:返回当个值
- 行子查询:返回单个记录
- 表子查询:返回一个临时表的子查询
标量子查询
(SELECT AVG(age) from test_age) 返回的是一个值,用这个值去过滤数据或者查询
行子查询
下面是在查询结果中的一行数据过滤,这里表中数据只有一条,实际这里可能有多条,这个sql查询没有意思,在此只做个示范。
表子查询
如下图在查询中在查询,或者将结果用于过滤数据。
- where 过滤,单个值可以使用关系运算,多个值可以使用IN 或者NOT IN
select * from test_age t where (t.age,t.name) in (SELECT age,name from test_age where age = 20)
- ALL、ANY运算符 类似于集合运算 ALL表示所有,ANY任意一个即可。
- FROM 查询中查询
关系子查询
使用查询结果作为另一个查询的
横向子查询
select d.dept_name as "部门名称", t.max_salary as "最高月薪" from deparment d cross join
lateral (select max(e.salary) as max_salary from employee e where e.dept_id = d.dept_id) t;
EXISTS
select d.dept_name as "部门名称"
from department d
where exists (select 1 from employee e
where e.sex="女" and e.dept_id = d.dept_id)
order by dept_name