openGauss每日一练第18天 | openGauss逻辑结构:视图管理
视图分为普通视图、物化视图。视图可以理解成一个虚拟表,数据来自基表。
普通视图,使用视图的时候,进行实时计算视图表示的结果集,将消耗很大的计算机资源,并且费时很长。
物化视图提前计算出视图的结果集,并将该结果集保持在数据库里。如果更新了基表,物化视图将过期。也就是说,基表更新后,物化视图不能反映最新的数据情况。因此在基表发生变化的时候,需要对物化视图进行更新。
1、创建表,创建普通视图
--查看表t1数据
omm=# select * from t1;
id | ename
----+-------
2 | app2
4 | app4
5 | app5
6 | app6
3 | app3
(5 rows)
--根据表t1创建视图v1
omm=# create view v1 as select * from t1 where id<=5;
CREATE VIEW
omm=# select * from v1;
(4 rows)
--查看视图数据
omm=# id | ename
----+-------
2 | app2
4 | app4
5 | app5
3 | app3
2、使用视图创建新的视图
omm=# select * from v1;
id | ename
----+----------
2 | app2
4 | app4
5 | app5
3 | app3
1 | zhangsan
(5 rows)
--使用视图v1创建视图vv1
omm=# create view vv1 as select * from v1 where ename like 'app%';
CREATE VIEW
omm=# select * from vv1;
id | ename
----+-------
2 | app2
4 | app4
5 | app5
3 | app3
(4 rows)
3、创建物化视图
omm=# create materialized view mv_t1 as select * from t1 where id<=5;
CREATE MATERIALIZED VIEW
omm=# select * from mv_t1;
id | ename
----+----------
2 | app2
4 | app4
5 | app5
3 | app3
1 | zhangsan
(5 rows)
--表t1新增一条id=0的数据
omm=# insert into t1 values(0,'gogogo');
INSERT 0 1
omm=# select * from t1;
id | ename
----+----------
2 | app2
4 | app4
5 | app5
6 | app6
3 | app3
1 | zhangsan
0 | gogogo
(7 rows)
--物化视图并没有看到这条id=0数据,需要我们更新物化视图才能看到这个新增id=0的数据
omm=# select * from mv_t1;
id | ename
----+----------
2 | app2
4 | app4
5 | app5
3 | app3
1 | zhangsan
(5 rows)
--通过数据字典查看新建的普通视图
select * from pg_views where schemaname = 'tpcds' or schemaname = 'public';
schemaname | viewname | viewowner | definition
------------+----------+-----------+--------------------------------------------
public | v1 | omm | SELECT * FROM t1 WHERE (t1.id <= 5);
public | vv1 | omm | SELECT * FROM v1 WHERE ((v1.ename)::text ~~ 'app%'::text);
(2 rows)
--查看物化视图
omm=# select * from gs_matview;
matviewid | mapid | ivm | needrefresh | refreshtime
-----------+-------+-----+-------------+-------------
16409 | 0 | f | |
(1 row)
4、手动更新物化视图
--更新物化视图mv_t1
omm=# refresh materialized view mv_t1;
REFRESH MATERIALIZED VIEW
--查看视图mv_t1,可以看到id=0的记录了
omm=# select * from mv_t1;
id | ename
----+----------
2 | app2
4 | app4
5 | app5
3 | app3
1 | zhangsan
0 | gogogo
(6 rows)
5、删除创建的视图
--不能直接删除视图v1,需要先删除依赖v1的视图vv1后,再来删除视图v1。或者使用cascade
omm=# drop view v1;
ERROR: cannot drop view v1 because other objects depend on it
DETAIL: view vv1 depends on view v1
HINT: Use DROP ... CASCADE to drop the dependent objects too.
--使用cascade级联操作后,把视图v1和vv1都一起删除了
omm=# drop view v1 cascade;
NOTICE: drop cascades to view vv1
DROP VIEW
omm=# drop view vv1;
ERROR: view "vv1" does not exist
--视图v1、vv1都删除了,并不影响表t1
omm=# \d t1
Table "public.t1"
Column | Type | Modifiers
--------+-----------------------+-----------
id | integer | not null
ename | character varying(50) |
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




