oracle子查询的使用

2025-12-29 18:25:54

1、子查询

1.概念

即一个select查询语句中嵌套了另外的一个或者多个select语句。

2.分类

(2.1)单行子查询

单行子查询即子查询结果为单个结果

示例1:在雇员表中查询出工资大于Alana雇员工资的所有雇员

oracle子查询的使用

2、示例2:在雇员表中查询出与Alana工作相同职位的雇员,但工资比Alana高

select first_name,salary,job_id from employees where job_id=(select job_id from employees where first_name='Alana') and salary>(select salary from employees where first_name='Alana');

oracle子查询的使用

3、(2.2)多行子查询

多行子查询即子查询返回结果为多个

查询出工作岗位和姓氏为Taylor两个人一样,但是工资却比姓氏为Taylor的两个人中的任意一个都高的雇员(大于任何一个人也就是大于最小)这里要使用到关键字any,它的意思就是大于任意值。

select last_name,salary,job_id from employees where job_id in(select job_id from employees where last_name='Taylor') and salary>any(select salary from employees where last_name='Taylor');

下图中可以看到姓氏为Taylor的有两个人,两个人的最小工资为3200,大于3200的所有数据都已经被查询出来了。

oracle子查询的使用

oracle子查询的使用

oracle子查询的使用

4、除了any之外还有一个关键字是all, 它的意思就是大于最大值。下图中可以看到,只有工资大于8200的数据才会被显示出来。

oracle子查询的使用

5、3.在子查询中也可以使用函数

示例:查询出工资最低的雇员是谁

select first_name,salary,job_id from employees where salary=(select min(salary) from employees);

oracle子查询的使用

6、同理要查询出工资最高的雇员是谁,只需要把min换成max即可

oracle子查询的使用

7、4.在子查询中也可以使用分组

示例:查询出每个部门工资最低的雇员。从下图中可以看出,子查询得出的结果并不是一行数据,所以要使用In.

oracle子查询的使用

8、但是还有问题,从图中可以看到,部门有的部门ID会出现两次,这显然不太符合每个部门工资最低的雇员这个要求。使用下面的语句可以解决。

select department_id,first_name,salary from employees e where salary in (select min(salary) from employees where e.department_id=department_id);

oracle子查询的使用

9、5.在子查询中也可以使用having子名对分组进行限制

示例:查询出哪些部门最低工资高于50部门

select department_id,min(salary) from employees group by department_id

having min(salary)>(select min(salary) from employees where department_id=50);

oracle子查询的使用

10、6.如果子查询的返回结果为空,那么主查询的结果也会为空,但不会报错。

示例:查询出工作ID与ceshi124的工作ID相同的雇员(事实上没有ceshi124的job_id)

oracle子查询的使用

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢