oracle-view

what is view

  • A view is a virtual table.
  • Views are built on the basis of existing tables, and these tables on which the view is built are called base tables.
  • The statement that provides data content to the view is SELECTa statement, and the view can be understood as a storedSELECT 语句
  • Views provide users with another representation of base table data

Why use views

  • Control data access
  • simplified query
  • Avoid repeated access to the same data

simple view and complex view

characteristic simple view complex view
number of tables one one or more
function No have
group No have
DML operations Can sometimes can

create view

  • CREATE VIEWEmbedding a subquery in a statement
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW 视图名称
  [(alias[, alias]...)]
 AS subquery
[WITH CHECK OPTION [CONSTRAINT 约束名称]]
[WITH READ ONLY [CONSTRAINT 约束名称]];

OR REPLACE: If the created attempt already exists, ORACLE will automatically rebuild the view;
FORCE: Regardless of whether the base table exists or not, ORACLE will automatically create the view;
subquery: A complete SELECT statement, in which an alias can be defined;
WITH CHECK OPTION : The data row inserted or modified must meet the constraints defined by the view;
WITH READ ONLY : No DML operation can be performed on the view.

  • Subqueries can be complex SELECT statements
-- 创建视图empview
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

Describe view structure

DESCRIBE empvu80
  • Define aliases for columns in subqueries when creating views
CREATE VIEW 	salvu50
 AS SELECT  employee_id ID_NUMBER, last_name NAME,
            salary*12 ANN_SALARY
    FROM    employees
    WHERE   department_id = 50;
  • Aliases should be used when selecting columns in a view
select ID_NUMBER,NAME,ANN_SALARY from salvu50;

View with check constraints

Requirement: Create a view VIEW_ADDRESS2 based on the address table (T_ADDRESS), the content of which is
the record whose area ID is 2.

-- 带检查约束的视图
create or replace view view_address2 as
select * from T_ADDRESS where areaid=2
with check option

Execute the following update statement:

-- 无法修改成功的语句,因为该视图的条件是areaid=2
update view_address2 set areaid=1 where id=4;

The system prompts the following error message:
insert image description here

read-only view

If we create a view and don't want users to be able to modify the view, then we need to
specify options when creating the view WITH READ ONLY , so that the created view is a read-only view

create or replace view view_owners1 as
select * from T_OWNERS where ownertypeid=1
with read only;

After the modification, execute the update statement again, and the following error message will appear
insert image description here

view with error

insert image description here

-- 视图来源的表根本不存在
-- 创建带错误的视图
create force view view_test as 
select * from t_test;

complex view

The so-called complex view refers to the SQL statement of the view, which contains aggregate functions or multi-table associated queries.

--复杂视图-多表关联
create or replace view view_owners as
select ow.id 业主编号,ow.name 业主名称,ot.name 业主类型  from t_owners ow,t_ownertype ot 
where ow.ownertypeid=ot.id;

insert image description here
Can this view modify the data?

update view_owners set 业主名称='范小冰' where 业主编号=1;

Can be modified successfully.
Try the following statement again

update view_owners set 业主类型='普通居民' where 业主编号=1;

You will find that the system pops up an error message:
insert image description here

-- 键保留表:把主键保留下来的那个表

What is a key reservation table?

A key-preserving table is a fundamental concept for understanding modification restrictions on join views. The primary key columns of the table are all displayed in the view
, and their values ​​are all unique and non-null in the view. That is to say, the key value of the table
is also the key value in a join view, then this table is called a key-preserving table.
In our example, there are two tables in the view, the owner table (T_OWNERS) and the owner type table
(T_OWNERTYPE), where the T_OWNERS table is the key reserved table, because
the primary key of T_OWNERS is also the primary key of the view. Fields of key-preserving tables can be updated, but non-key-preserving tables cannot
.

View of Aggregated Statistics

Views of aggregated statistics cannot be modified

--聚合统计的复杂视图
create view view_accountsum as
select year,month,sum(money) money
from t_account 
group by year,month
order by year,month;

query view data
insert image description here

--能修改吗?--答:不能的。
update view_accountsum set month='04' where year='2012' and month='03'

materialized view

What is a materialized view

A view is a virtual table (which can also be thought of as a statement) based on
the result set returned by the query statement specified when it was created. Each access to it will cause the query statement to be executed once. In order to avoid
executing this query every time you access it, you can store the query result set in a materialized view (also called a materialized
view).
The difference between a materialized view and an ordinary view is that a materialized view is a created copy, which is similar to a
table and requires storage space. The execution efficiency of querying a materialized view is the same as querying a table
.

Create materialized view syntax

CREATE METERIALIZED VIEW view_name
[BUILD IMMEDIATE | BUILD DEFERRED ]
REFRESH [FAST|COMPLETE|FORCE]
[
ON [COMMIT |DEMAND ] | START WITH (start_time) NEXT
(next_time)
]
AS
subquery

BUILD IMMEDIATE generates data when creating a materialized view.
BUILD DEFERRED does not generate data when creating a materialized view, and generates data later as needed.
The default is BUILD IMMEDIATE. Refresh (REFRESH): Refers to when and which method the materialized view uses to synchronize with the base
table after a DML operation occurs on the base table. REFRESH followed by the specified refresh method has three: FAST, COMPLETE, FORCE. FAST refresh uses incremental refresh, and only refreshes the modifications made since the last refresh. COMPLETE refresh performs a complete refresh of the entire materialized view. If you choose the FORCE method, Oracle will judge whether fast refresh is possible when refreshing . If it is possible, it will use the FAST method, otherwise it will use the COMPLETE method. FORCE is the default. There are two refresh modes: ON DEMAND and ON COMMIT. ON DEMAND means that the materialized view needs to be manually refreshed (default). ON COMMIT refers to automatic refresh when a COMMIT operation occurs on the base table








the case

1. Create a manually refreshed materialized view

--COMPLETE  完全刷新  
--FAST      增量更新
--FORCE     自动选择

--ON COMMIT   在基表做提交操作是刷新物化视图
--ON DEMAND   手动刷新
--创建手动刷新的物化视图
create materialized view view_address1 as
select ad.id,ad.name,ar.name arname from t_address ad,t_area ar
where ad.areaid=ar.id

After the statement is successfully executed, you can see the newly created view in Materialized views, and create a table in the corresponding table space
insert image description here
insert image description here

delete materialized view

drop materialized view 视图名称;

query materialized view


--查询物化视图
select * from mv_address1
--创建时不生成数据的物化视图

create materialized view mv_address3
build deferred
refresh 
on commit
as
select ad.id,ad.name,ar.name arname from t_address ad,t_area ar
where ad.areaid=ar.id



insert into T_ADDRESS VALUES(12,'西7旗',2,2);
commit;
-- 使用sql语句进行查询,会发现新插入的语句并没有出现在物化视图中
--查询物化视图
select * from mv_address3
-- 我们需要通过下面的语句(PL/SQL),手动刷新物化视图:
--第一次必须手动执行刷新,
begin
 DBMS_MVIEW.refresh('MV_ADDRESS3','C');
end;

Or manually refresh the materialized view with the following command:

EXEC DBMS_MVIEW.refresh('MV_ADDRESS3','C');
-- 注意:此语句需要在命令窗口中执行。
-- 执行此命令后再次查询物化视图,就可以查询到最新的数据了。

DBMS_MVIEW.refresh is actually a built-in stored procedure in the system
Open the command window in pl/sql
insert image description here
insert image description here

Create an automatically refreshed materialized view

The statement is as follows:


--创建自动刷新的物化视图  -基表发生commit操作,自动刷新物化视图
create materialized view mv_address2
refresh 
on commit
as
select ad.id,ad.name,ar.name arname from t_address ad,t_area ar
where ad.areaid=ar.id

After creating this materialized view, when the T_ADDRESS table changes, MV_ADDRESS2 will automatically
change accordingly.

--向基表插入数据
insert into T_ADDRESS VALUES(10,'西5旗',2,2);
commit;
--查询物化视图
select * from mv_address2;

Materialized views that do not generate data when created

-- 创建时不生成数据的物化视图

create materialized view mv_address3
build deferred
refresh 
on commit
as
select ad.id,ad.name,ar.name arname from t_address ad,t_area ar
where ad.areaid=ar.id;
--查询物化视图
select * from mv_address3

insert into T_ADDRESS VALUES(12,'西7旗',2,2);
commit;
-- 由于我们创建时指定的 on commit ,所以在修改数据后能立刻看到最新数据,无须
--再次执行 refresh 
--第一次必须手动执行刷新,
begin
 DBMS_MVIEW.refresh('MV_ADDRESS3','C');
end;

Create an incrementally refreshed materialized view

If you create an incrementally refreshed materialized view, you must first create a materialized view log

--.创建增量刷新的物化视图

--前提是必须创建物化视图日志 :记录基表发生了哪些变化,用这些记录去更新物化视图
create materialized view log on t_address with rowid;
create materialized view log on t_area with rowid;

The created materialized view log name is MLOG$_table name
insert image description here
Create materialized view

--创建物化视图中的语句中,必须有基表的ROWID

create materialized view mv_address4
refresh fast
as
select ad.rowid adrowid,ar.rowid arrowid, ad.id,ad.name,ar.name arname from t_address ad,t_area ar
where ad.areaid=ar.id;

Note: To create a materialized view with incremental refresh, you must:

  1. Create a materialized view log for the tables involved in the materialized view.
  2. In the query statement, the rowid of all tables must be included (the materialized view log is created in rowid mode).
    When we insert data into the address table, the content of the materialized view log:
--插入数据 
insert into T_ADDRESS VALUES(14,'西9旗',2,2);

insert image description here
SNAPTIME$$: Used to indicate the refresh time.
DMLTYPE$$: Used to indicate the type of DML operation, I means INSERT, D means DELETE, U means UPDATE.
OLD_NEW$$: Used to indicate whether this value is a new value or an old value. N(EW) means new value, O(LD)
means old value, U means UPDATE operation.
CHANGE_VECTOR$$: Indicates the modification vector, which is used to indicate which field or fields are modified.
This column is of RAW type. In fact, the way Oracle uses is to use each BIT bit to map a column.
Insert operations are displayed as: FE, delete operations are displayed as: OO and update operations display
different values ​​depending on the position of the updated field.
When we manually refresh the materialized view, the materialized view log is cleared and the materialized view is updated.

begin
DBMS_MVIEW.refresh('MV_ADDRESS4','C');
end;

modify view

  • Use CREATE OR REPLACE VIEW clauses to modify views
  • The aliases of the columns in the CREATE VIEW clause should correspond to the columns in the subquery
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;

Rules for using DML in views

  • DML operations can be performed in a simple view
  • cannot be used when the view definition contains one of the following elementsdelete:
          组函数
          GROUP BY 子句
          DISTINCT 关键字
          ROWNUM 伪列
create or replace view sal_view
as select
avg(salary) avg_sal from employees
group by department_id
  • Cannot be used when the view definition contains one of the following elements update:
    组函数
    GROUP BY子句
    DISTINCT 关键字
    ROWNUM 伪列
    列的定义为表达式
  • Cannot be used when the view definition contains one of the following elementsinsert:
    组函数
    GROUP BY 子句
    DISTINCT 关键字
    ROWNUM 伪列
    列的定义为表达式
    表中非空的列在视图定义中未包括

Block DML operations

  • WITH READ ONLYDML operations on views can be blocked using the option
  • Any DMLoperation returns an Oracle servererror
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;

delete view

Deleting a view only deletes the definition of the view, and does not delete the data of the base table

drop view 视图名称;

Guess you like

Origin blog.csdn.net/Java_Fly1/article/details/124723252