oracle子查询的使用
1、子查询1.概念即一个select查询语句中嵌套了另外的一个或者多个select语句。2.分类(2.1)单行子查询单行子查询即子查询结果为单个结果示例1:在雇员表中查询出工资大于Alana雇员工资的所有雇员
2、示例2:在雇员表中查询出与Alana工作相同职位的雇员,但工资比Alana高select first_name,salar烤恤鹇灭y,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');
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的所有数据都已经被查询出来了。
4、除了any之外还有一个关键字是all, 它的意思就是大于最大值。下图中可以看到,只有工资大于8200的数据才会被显示出来。
5、3.在子查询中也可以使用函数示例:查询出工资最低的雇员是谁select first_name,salary,job_id from employees where salary=(select min(salary) from employees);
6、同理要查询出工资最高的雇员是谁,只需要把min换成max即可
7、4.在子查询中也可以使用分组示例:查询出每个部门工资最低的雇员。从下图中可以看出,子查询得出的结果并不是一行数据,所以要使用In.
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);
9、5.在子查询中也可以使用having子名对分组进行限制示例:查询出哪些部门最低工资高于50部门select department_id,min(salary) from employees group by department_idhaving min(salary)>(select min(salary) from employees where department_id=50);
10、6.如果子查询的返回结果为空,那么主查询的结果也会为空,但不会报错。示例:查询出工作ID与ceshi124的工作ID相同的雇员(事实上没有ceshi124的job_id)