Oracle inline view 简介

来源:互联网 发布:影视app源码 编辑:程序博客网 时间:2024/06/18 09:52

什么是inline view?

其实很简单.   inline view 就是指 from 后面出现另1个select 语句.


例如最简单的inline view 用法

select table_name from (select * from user_tables) 

当然上面的inline view用法很多余


让我们看看下面的例子:



19.View the Exhibit and examine PRODUCTS and ORDER_ITEMS tables. You executed the following query to display PRODUCT_NAME and the number of times the product has been ordered:
SELECT p.product_name, i.item_cnt FROM (SELECT product_id, COUNT (*) item_cnt FROM order_items GROUP BY product_id) i RIGHT OUTER JOIN products p ON i.product_id = p.product_id;
What would happen when the above statement is executed?
A. The statement would execute successfully to produce the required output.
B. The statement would not execute because inline views and outer joins cannot be used together.
C. The statement would not execute because the ITEM_CNT alias cannot be displayed in the outer query.
D. The statement would not execute because the GROUP BY clause cannot be used in the inline view.




我们来做个实践

首先建表和插入数据

create table products(                       product_id number(4),                       product_name varchar2(20));                      create table order_items(                      order_id number(4),                      product_id number(4),                      qty number(4),                      unit_price number(6));                                            insert into products select 1, 'Inkjecet C/8/HQ' from dual;insert into products select 2, 'CPU D300' from dual;insert into products select 3, 'HD 8GB/I' from dual;insert into products select 4, 'HD 12GB/R' from dual;commit;insert into order_items select 11,1,10,100 from dual;insert into order_items select 22,2,15,120 from dual;insert into order_items select 33,3,10,50 from dual;insert into order_items select 44,1,5,10 from dual;insert into order_items select 66,2,20,125 from dual;commit;

在分析下题目中的select 语句:

SQL>  select product_id, count(1) item_cnt from order_items group by product_id;PRODUCT_ID   ITEM_CNT---------- ---------- 1    2 2    2 3    1SQL> 

select p.product_name, i.item_cnt
from  (select product_id, count(1) item_cnt
        from   order_items
        group by product_id)
iright outer join products p
                                              on   p.product_id = i.product_id



可见 红色的select 语句部分被作为1个别称为 i 的表 与  products 表 右连接.

红色部分的执行结果:

SQL>  select product_id, count(1) item_cnt from order_items group by product_id;PRODUCT_ID   ITEM_CNT---------- ---------- 1    2 2    2 3    1SQL> 

表 products的数据

PRODUCT_ID PRODUCT_NAME---------- -------------------- 1 Inkjecet C/8/HQ 2 CPU D300 3 HD 8GB/I 4 HD 12GB/RSQL> 

所以右连接后. (右边的数据无对应左边数据的话显示右边的数据)

就成为:

PRODUCT_NAME       ITEM_CNT-------------------- ----------Inkjecet C/8/HQ       2CPU D300      2HD 8GB/I      1HD 12GB/R


所以题目的select 语句是能正确执行的.


答案是A