视图定义:
— —视图是一种虚表。
— —视图建立在已有表的基础上, 视图赖以建立的这些表称为基表。
为什么使用视图?
— —控制数据访问
— —简化查询
— —避免重复访问相同的数据
创建视图:在 CREATE VIEW 语句中嵌入子查询,子查询可以是复杂的 SELECT 语句
<span style="font-size:14px;">create or replace view empview as select employee_id emp_id,last_name name,department_name from employees e,departments d Where e.department_id = d.department_id</span>
<span style="font-size:14px;">CREATE VIEW salvu50 AS SELECT employee_id ID_NUMBER, last_name NAME, salary*12 ANN_SALARY FROM employees WHERE department_id = 50; View created.</span>
查询视图:SELECT * FROM salvu50;
修改视图:使用CREATE OR REPLACE VIEW 子句修改视图
<span style="font-size:14px;">CREATE OR REPLACE VIEW empvu80 (id_number, name, sal, department_id) AS SELECT employee_id, first_name || ' ' || last_name, salary, department_id FROM employees WHERE department_id = 80; View created.</span>CREATE VIEW 子句中各列的别名应和子查询中各列相对应
<span style="font-size:14px;">CREATE VIEW dept_sum_vu (name, minsal, maxsal, avgsal) AS SELECT d.department_name, MIN(e.salary), MAX(e.salary),AVG(e.salary) FROM employees e, departments d WHERE e.department_id = d.department_id GROUP BY d.department_name; View created.</span>
可以在简单视图中执行 DML 操作
当视图定义中包含以下元素之一时不能使用delete:
— —组函数
— —GROUP BY 子句
— —DISTINCT 关键字
— —ROWNUM 伪列
<span style="font-size:14px;">create or replace view sal_view as select avg(salary) avg_sal from employees group by department_id </span>
当视图定义中包含以下元素之一时不能使insert:
— —组函数
— —GROUP BY 子句
— —DISTINCT 关键字
— —ROWNUM 伪列
— —列的定义为表达式
— —表中非空的列在视图定义中未包括
屏蔽 DML 操作:
可以使用 WITH READ ONLY 选项屏蔽对视图的DML 操作
任何 DML 操作都会返回一个Oracle server 错误
<span style="font-size:14px;">CREATE OR REPLACE VIEW empvu10 (employee_number, employee_name, job_title) AS SELECT employee_id, last_name, job_id FROM employees WHERE department_id = 10 WITH READ ONLY; View created.</span>
<span style="font-size:14px;">DROP VIEW empvu80; View dropped.</span>
查询最大的几个值的 Top-N 分析:
<span style="font-size:14px;">SELECT [column_list], ROWNUM FROM (SELECT [column_list] FROM table ORDER BY Top-N_column) WHERE ROWNUM <= N;</span>注意:
<span style="font-size:14px;">select * from( select rownum rn,employee_id,salary from( select employee_id,salary,last_name from employees order by salary desc ) )where rn <=50 and rn >40</span>
原文地址:http://blog.csdn.net/yuzongtao/article/details/40601993