子查询语法:
子查询 (内查询) 在主查询之前一次执行完成。
子查询的结果被主查询使用 (外查询)。
注意事项:
子查询要包含在括号内。
将子查询放在比较条件的右侧。
单行操作符对应单行子查询,多行操作符对应多行子查询。
子查询类型:
单行子查询
只返回一行。
使用单行比较操作符
执行单行子查询:
SQL> select last_name from employees where salary>(select salary from employees where last_name='Abel');
在查询中使用组函数:
SQL> select last_name,job_id,salary from employees where salary=(select min(salary) from employees);
子查询中的having子句:
首先执行子查询。
向主查询中的HAVING 子句返回结果。
SQL> select department_id,min(salary) from employees group by department_id having min(salary)>(select min(salary) from employees where department_id=50);
多行子查询
返回多行。
使用多行比较操作符
操作符 含义
In 等于列表中的任何一个
Any 和子查询返回的任意一个值比较
All 和子查询返回的所有值比较
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'
子查询中的空值问题:
SQL> select emp.last_name from employees emp where emp.employee_id not in(select mgr.manager_id from employees mgr);