Oracle SQL Lesson (7) - 使用子查询

时间:2022-06-29 13:10:31

使用子查询
简单子查询
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
子查询可以出现在select,from和where之后,都是可以的。
SELECT last_name, salary
FROM employees
WHERE salary >
(SELECT salary
FROM employees
WHERE last_name = 'Abel');

SELECT last_name, job_id, salary
FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE last_name = 'Taylor')
AND salary >
(SELECT salary
FROM employees
WHERE last_name = 'Taylor');

在当行子查询中使用组函数(仅返回单行)
SELECT last_name, job_id, salary
FROM employees
WHERE salary =
(SELECT MIN(salary)
FROM employees);

SELECT department_id, MIN(salary)
FROM employees
GROUP BY department_id
HAVING MIN(salary) >
(SELECT MIN(salary)
FROM employees
WHERE department_id = 50);

错误:在单行操作符后边返回多行记录
SELECT employee_id, last_name
FROM employees
WHERE salary =
(SELECT MIN(salary)
FROM employees
GROUP BY department_id);

多行子查询
SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary < ANY
(SELECT salary
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';

SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary < ALL
(SELECT salary
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';

使用存在操作符exists
只关心存在,不关心数量;in关心数量
select empno,ename from emp where emp.empno in(select mgr from emp); (找到之后继续比较)
select empno,ename from emp o where exists(select 1 from emp i where o.empno=i.mgr);(找到之后不再比较)

select empno,ename from emp where emp.empno not in(select mgr from emp where mgr is not null); (找到之后继续比较)
select empno,ename from emp o where not exists(select 1 from emp i where o.empno=i.mgr);(找到之后不再比较)