子查询
子查询是指在查询语句的内部嵌入查询,以获取临时的结果集。Oracle总是自动优化带子查询的查询语句。如果子查询中的数据源与父查询中的数据可以实现连接操作,那么将转换为连接操作;否则,将首先执行子查询,然后执行父查询。
-
查询条件中的子查询
-
例如
-
student 表
-
class 表
-
问题:查询student 表中不存在的年级
- select * from class where class_name not in (select distinct class from student);
-
-
select 列名1,列名2 … from 表名 where 列名 运算符 ( 子查询 );
- 注意:这里的子查询实际返回的结果集只能有一列
-
-
建表语句中的子查询
-
create table 表名 as 子查询
-
例如:
-
student 表
-
将查询class 为一年级的放入 class_one 表中
- create table class_one as select * from student where class=‘一年级’;
-
-
-
插入语句中的子查询
-
相当于向表中批量插入数据
-
例如:
-
student 表
-
class_one 表
-
向class_one 表中插入 class 为二年级的数据
- insert into class_one select * from student where class=‘二年级’;
-
-