Oracle之視圖與索引(四)

視圖:

建立在表|結果集|視圖上的虛擬表,有以下作用:
	1、簡化:select查詢語句
	2、重用:封裝select語句 命名
	3、隱藏:內部細節
	4、區分:相同數據不同查詢
不是所有的用戶都有創建視圖的權限
	1、前提:create view -->組 connect resource dba
	2、授權   -->sqlplus/nolog
		a)、sys登錄 	conn  sys/123456  as  sysdba
		b)、授權:grant dba to scott;
  			回收:revoke dba from scott; 
		c)、重新登錄

語法:create or replace view 視圖名 as select語句[with read only];
要求:所有列必須存在名稱。
對視圖的刪除不會刪除原有表的數據
drop view 視圖名;
求部門經理人中平均薪水最低的部門名稱
--部門經理人 -->mgr
create or replace view vw_emp_mgr as select distinct mgr from emp
where mgr is not null with read only;
--部門經理人的薪水
create or replace view vw_emp_mgr_sal as
select *
from emp
where empno in (select mgr from vw_emp_mgr) with read only;
--按部門平均
create or replace view vw_emp_sal_group as select deptno,avg(sal)
avgsal from vw_emp_mgr_sal group by deptno with read only;
--過濾組

--找出最低的平均薪水
--使用第三個視圖
select min(avgsal) from vw_emp_sal_group
--使用第二個視圖
select min(avg(sal)) minsal from vw_emp_mgr_sal group by deptno;
--獲取部門編號及平均薪水
select *
from vw_emp_sal_group
where avgsal =
(select min(avg(sal)) minsal from vw_emp_mgr_sal group by
deptno);
--部門名稱
select dname
from vw_emp_sal_group vw, dept d
where vw.deptno = d.deptno
and avgsal =
(select min(avg(sal)) minsal from vw_emp_mgr_sal group by
deptno);

五、索引

索引是數據庫對象之一,用於加快數據的檢索,類似於書籍的索引。在數據庫中索引可以減少數據庫程序查詢結果時需要讀取的數據量
索引是建立在表上的可選對象;索引的關鍵在於通過一組排序後的索引鍵來取代默認的全表掃描檢索方式,從而提高檢索效率
索引在邏輯上和物理上都與相關的表和數據無關,當創建或者刪除一個索引時,不會影響基本的表;
索引一旦建立,在表上進行 DML 操作時(例如在執行插入、修改或者刪除相關操作時),oracle 會自動管理索引,索引刪除,不會對錶產生影響
oracle 創建主鍵時會自動在該列上創建索

索引好處: 提高查詢速度的一種手段
	1、唯一性較好字段適合建立索引
	2、大數據量纔有效果
	3、主鍵|唯一: 唯一索引
--create index 索引名 on表名 (字段列表...)
create index index_emp_sal on emp(sal);
--drop index 索引名
drop index index_emp_sal;

select * from emp where sal>800;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章