Oracle一直以来就支持一种叫做“串联视图(in-line view)”的概念,其中子查询SELECT可以出现在FROM子句中,就似乎它是表名一样。 下面是一个一般由DBA用来显示表空间大小的Oracle查询。注重它在FROM子句中使用了SELECT语句。这就叫做串联视图。
select df.tablespace_name "Tablespace", block_size "Block Size", (df.totalspace - fs.freespace) "Used MB", fs.freespace "Free MB", df.totalspace "Total MB", round(100 * (fs.freespace / df.totalspace)) "Pct. Free" from dba_tablespaces ts, (select tablespace_name, round(sum(bytes) / 1048576) TotalSpace from dba_data_files group by tablespace_name) df, (select tablespace_name, round(sum(bytes) / 1048576) FreeSpace from dba_free_space group by tablespace_name) fs where ts.tablespace_name = fs.tablespace_name and df.tablespace_name = fs.tablespace_name(+) ; Tablespace Block Size Used MB Free MB Total MB Pct. Free --------------- ----------- ----------- ------------ ----------- ---------- CWMLITE 4,096 6 14 20 70 DRSYS 4,096 8 12 20 60 EXAMPLE 4,096 153 0 153 0 INDX 4,096 0 25 25 100 SYSTEM 4,096 241 84 325 26 TOOLS 4,096 7 3 10 30 TS_16K 16,384 3 7 10 70 UNDOTBS 4,096 1 199 200 100 USERS 4,096 1 24 25 96 到了Oracle9i,你可以往SELECT子句中直接添加子查询。在下面的这个例子中我们将选出一个表的MAX值和AVG值以及具体的行数据。 select (select max(salary) from emp) highest_salary, emp_name employee_name, (select avg(bonus) from commission) avg_comission, dept_name from emp, (select dept_name from dept where dept = 'finance') ; 你也可以直接地将子查询放到插入语句的VALUES子句中: insert into max_credit ( name, max_credit ) values ( 'Bill', select max(credit) from credit_table where name = 'BILL' ); 注重标量子查询有一些限制,在以下这些情况中不能使用: ● 某个列的默认值 ● RETURNING子句 ● 聚簇的哈希表达式 ● 功能索引表达式 ● 在列上的CHECK约束 ● 触发器的WHEN条件 ● GROUP BY和HAVING子句 ● START WITH和CONNECT BY子句 标量子查询为Oracle SQL提供了一个强大的新工具。虽然其语法比较晦涩有时候很难使用,但是标量子查询能将几个查询组合到一个单独的SQL单元中使它们可以在一个单独的单元中被执行。这大大简化了复杂的SQL计算。标量子查询对于数据仓库应用和那些需要复杂SQL查询的数据库来说尤其有用。
|