oracle教程:简单视图、带检查约束的视图、只读视图、带错误的视图、多表关联的视图、聚合统计的视图 短命女 2023-10-15 09:53 64阅读 0赞 ## 什么是视图 ## 1、 要点:对sql语句的一种封装,它是一个虚拟的表。 2、 使用场景:对经常需要查询的数据,进行封装。 3、 优点:提高工作效率。 ## 创建修改删除视图语法 ## > 要点:创建视图的基本语法和删除视图。 1、创建视图 CREATE [OR REPLACE] [FORCE] VIEW view_name AS subquery [WITH CHECK OPTION ] [WITH READ ONLY] REPLACE:删除已有视图,重新创建视图。 FORCE:不管基表是否存在,都会创建视图。 WITH CHECK OPTION:插入或修改的数据行必须满足视图定义的约束。 WITH READ ONLY:只读。 2、删除视图: DROP VIEW view_name ## 视图案例-简单视图 ## > 要点:视图中查询的表称之为基表,修改视图实际就是在修改基表中的数据。视图在数据库中实际上就是一条sql语句,查询视图的数据实际就是在查询基表的数据。 1、--需求:创建视图 :业主类型为 1 的业主信息 create view view_owners1 as select * from t_owners where ownertypeid = 1; 2、--查询简单视图 select * from view_owners1 where addressid = 1; 3、--修改视图数据 update view_owners1 set name='范小冰' where id=1; commit; 4、--查询表 select * from t_owners where ownertypeid = 1; ## 视图案例-检查约束的视图 ## > 要点:视图中添加with check option选项,无法修改视图中基表的条件字段。 1、--带检查约束的视图 --需求:根据地址表(T_ADDRESS)创建视图 VIEW_ADDRESS2 ,内容为区域 ID为 2 的记录。 create view view_address2 as select * from t_address where areaid=2 with check option 2、--无法修改成功的语句,因为该视图的条件是areaid=2 update view_address2 set areaid=3 where id=4; 3、--可以修改成功的语句,因为条件不是areaid update view_address2 set name='河畔花园1' where id=4; commit; ## 视图案例-只读视图 ## > 要点: 视图中添加or replace删除原有视图,重新创建视图,添加with read only视图只能查看不能修改。 1、--需求:将上边的视图修改为只读视图 create or replace view view_owners1 as select * from t_owners where ownertypeid=1 with read only 2、--修改只读视图数据 update view_owners1 set name='aaa' where id=1; ## 视图案例-带错误的视图 ## > 要点:视图中添加 force选项可以创建数据库中没有的表。 --创建带错误的视图 create force view view_test as select * from t_test ## 视图案例-多表关联的视图 ## > 要点: > 复杂视图:视图的 SQL 语句中,有聚合函数或多表关联查询。 > 键保留表:把主键保留下来的那个表。 1、--创建视图,查询显示业主编号,业主名称,业主类型名称 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 2、--查询复杂视图(多表关联) select * from view_owners where 业主类型='居民'; 3、--修改键保留表复杂视图(多表关联)的数据 update view_owners set 业主名称='林玲玲' where 业主编号=4; commit; 4、--修改非键保留表复杂视图(多表关联)的数据 update view_owners set 业主类型='商业' where 业主编号=4; --键保留表:把主键保留下来的那个表 ## 视图案例-聚合统计的视图 ## > 要点:聚合统计视图默认是只读,无法修改数据。 1、--需求:创建视图,按年月统计水费金额 create view view_accountsum as select year,month,sum(money) money from t_account group by year,month order by year,month 2、--查询视图 select * from view_accountsum where year='2012' and month='03' 3、--不能修改 update view_accountsum set money=10000 where year='2012' and month='03'
还没有评论,来说两句吧...