Oracle数据库学习(6)子查询

概述:在查询时基于未知的值时,可以使用子查询。

1、查询工资比Abel高的员工

SELECT LAST_NAME,SALARY FROM EMPLOYEES WHERE SALARY>(SELECT SALARY FROM EMPLOYEES WHERE LAST_NAME='Abel')

Oracle数据库学习(6)子查询

2、查询员工名为Chen的manage的信息

SELECT EMPLOYEE_ID,LAST_NAME,SALARY FROM EMPLOYEES WHERE EMPLOYEE_ID=(SELECT MANAGER_ID FROM EMPLOYEES WHERE LAST_NAME='Chen')

Oracle数据库学习(6)子查询

3、查询job_id与员工id为141号的员工相同,salary比143号员工多的员工,job_id和工资

SELECT LAST_NAME,JOB_ID,SALARY FROM EMPLOYEES WHERE JOB_ID=(SELECT JOB_ID FROM EMPLOYEES WHERE EMPLOYEE_ID=141)
AND SALARY>(SELECT SALARY FROM EMPLOYEES WHERE EMPLOYEE_ID=143)

Oracle数据库学习(6)子查询

 

4、查询最低工资大于50号部门最低工资的部门id和其最低工资

SELECT DEPARTMENT_ID,MIN(SALARY) FROM EMPLOYEES GROUP BY DEPARTMENT_ID 
HAVING MIN(SALARY)>(SELECT MIN(SALARY) FROM EMPLOYEES WHERE DEPARTMENT_ID=50)

Oracle数据库学习(6)子查询

 

5、查询和Zlotkey相同部门的员工姓名和雇用日期

select last_name,hire_date from employees where department_id = (select department_id from employees where last_name = 'Zlotkey')
and last_name <> 'Zlotkey'

Oracle数据库学习(6)子查询

 

6、查询各部门中工资比本部门平均工资高的员工的员工号, 姓名和工资

select employee_id,last_name,salary from employees e1 where salary > (select avg(salary) from employees e2 where e1.department_id = e2.department_id group by department_id)

Oracle数据库学习(6)子查询

 

 

7、查询和姓名中包含字母u的员工在相同部门的员工的员工号和姓名

select employee_id,last_name from employees where department_id in (select department_id from employees
where last_name like '%u%') and last_name not like '%u%';

 

8、查询在部门的location_id为1700的部门工作的员工的员工号

select employee_id from employees where department_id in (select department_id from departments where location_id = 1700)

Oracle数据库学习(6)子查询

 

9、查询管理者是King的员工姓名和工资

select last_name,salary from employees where manager_id in (select employee_id from employees where last_name = 'King')

Oracle数据库学习(6)子查询

 

10、查询员工的last_name, department_id, salary.其中员工的salary,department_id与有奖金的任何一个员工的salary,department_id相同即可

select last_name,department_id,salary from employees where (salary,department_id) in
(select salary,department_id from employees where commission_pct is not null )

Oracle数据库学习(6)子查询

 

11、选择工资大于所有JOB_ID = 'SA_MAN'的员工的工资的员工的last_name, job_id, salary

select last_name,job_id,salary from employees
where salary > all(select salary from employees where job_id = 'SA_MAN')

Oracle数据库学习(6)子查询

 

12、 选择所有没有管理者的员工的last_name

select last_name from employees e1
where not exists (select 'A' from employees e2 where e1.manager_id = e2.employee_id)

Oracle数据库学习(6)子查询

上一篇:oracle sql ,分隔的字段去关联查询另一张表的信息


下一篇:Oracle数据库学习(7)增删改操作与事务控制