#1、标量子查询(单行子查询) #①查询Abel的工资 select salary from employees where last_name = 'Abel'; #查询员工的信息,满足 salary>①结果 select * from employees where salary > ( select salary from employees where last_name = 'Abel' );
#②返回job_id与141号员工相同,salary比143号员工多的员工姓名,job_id和工资 #第一步:①查询141号员工的job_id select job_id from employees where employee_id = 141; #第二步:②查询143号员工的salary select salary from employees where employee_id = 143; #第三步:查询员工的姓名,job_id和工资,要求job_id=①并且salary>② 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 );
#查询最低工资大于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 );
#2、列子查询(多行子查询) #返回location_id是1400或1700的部门中的所有员工姓名 select last_name from employees where department_id in( select distinct department_id from departments where location_id in(1400, 1700) ); #或 select last_name from employees where department_id =any( select distinct department_id from departments where location_id in(1400, 1700) );
#返回location_id不是1400或1700的部门中的所有员工姓名 select last_name from employees where department_id not in( select distinct department_id from departments where location_id in(1400, 1700) ); #或 select last_name from employees where department_id <>all( select distinct department_id from departments where location_id in(1400, 1700) );
#返回其他部门(意思是除去部门IT_PROG的)中比job_id为'IT_PROG'工种任一工资低的员工的员工号、姓名、job_id以及salary #一、先查询job_id为'IT_PROG'工种任一工资 select distinct salary from employees where job_id = 'IT_PROG'; #二、查询员工号、姓名、job_id以及salary,salary < (一)的任意一个 select last_name, employee_id, job_id, salary from employees where salary < any( select distinct salary from employees where job_id = 'IT_PROG' ) and job_id <> 'IT_PROG'; #或 select last_name, employee_id, job_id, salary from employees where salary < ( select max(salary) from employees where job_id = 'IT_PROG' ) and job_id <> 'IT_PROG';
#返回其他部门(意思是除去部门IT_PROG的)中比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 last_name, employee_id, job_id, salary from employees where salary < ( select min(salary) from employees where job_id = 'IT_PROG' ) and job_id <> 'IT_PROG';
#3、行子查询(多行多列) #查询员工编号最小并且工资最高的员工信息 select * from employees where (employee_id, salary) = ( select min(employee_id), max(salary) from employees )
|