1、子查询简介
1.1 子查询语法:
SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table);
1.2 注意:
a.子查询要包含在括号内;
b.将子查询放在比较条件的右侧;
c.单行操作对应单行子查询,多行操作对应多行子查询;
2、单行子查询
单行子查询只返回一行,单行比较操作符有:
操作符 | 含义 |
= | 等于 |
> | 大于 |
>= | 大于等于 |
< | 小于 |
<= | 小于等于 |
<> | 不等于 |
例如:
返回job_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);
2.1 在子查询中使用子函数
例如:返回公司工资最少的员工的last_name,job_id和salary
SELECT last_name, job_id, salary FROM employees WHERE salary = (SELECT MIN(salary) FROM employees);
#多行子查询使用单行比较符 SELECT employee_id, last_name FROM employees WHERE salary = (SELECT MIN(salary) FROM employees GROUP BY department_id); ERROR at line 4: ORA-01427: single-row subquery returns more thanone row
子查询中的空值问题:
SELECT last_name, job_id FROM employees WHERE job_id = (SELECT job_id FROM employees WHERE last_name = 'Haas');
3.多行子查询
多行子查询返回多行,应该使用多行比较操作符
操作符 | 含义 |
in | 等于列表中的任意一个 |
any | 和子查询返回的某一个值比较 |
all | 和子查询返回的所有值比较 |
3.1在子查询中使用any操作符
--返回其它部门中比job_id为‘IT_PROG’部门任一工资低的员工的员工号、姓名、job_id 以及salary 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';
3.2在子查询中使用all操作符
--返回其它部门中比job_id为‘IT_PROG’部门所有工资都低的员工的员工号、姓名、job_id 以及salary 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';
3.3子查询中的控制问题
SELECT emp.last_name FROM employees emp WHERE emp.employee_id NOT IN (SELECT mgr.manager_id FROM employees mgr); --no rows selected
参考资料:尚硅谷数据库学习