1.什么是视图
是一个逻辑表(不是真实存在的),
基于一个表或一个视图
作用:
为了数据的安全
工作原理:
视图先执行查询
需要先赋权限
2.语法:
create 【or replace】【force】【noforce】 viewName (【别名列表】) as 查询语句
【with check option【constraint constraint_name】】
【with read only】
例子: create or replace force view view_books("id") as (select id from books) with read only;
force:
强制,
表不存在也能创建成功
noforce:
不强制,
默认是不强制
别名列表:
为视图中的字段起别名
别名个数需要和查询语句中查询字段的个数一致
查询语句
查询语句中不能使用order by 排序?
可以使用,但是使用之后后面不能加其他东西,比如:with read only,
所以需要排序的时候可以在使用视图的时候进行排序
查询如果是多表查询,则不允许通过视图对基表进行修改和删除操作8n
with check option:
用来限制DML操作
如果是添加或修改数据,则添加后的数据或修改中的数据,必须能在视图中查到,
即必须满足子查询的where条件
如果是删除数据
删除的数据在where字句范围内,则可以成功删除基表中的数据
但是数据不在where字句范围内,则虽然删除成功,但是并没有影响基表中的数据
例子:
create or replace view student_view as select * from student where age<20 with check option;
create or replace view student_view
as select * from student where age<20
with check option;
select * from student_view;
--ORA-01402: 视图 WITH CHECK OPTIDN where 子句违规
update student_view set age='22' where id='103'
--插入成功
insert into student_view values('106','小王',15,null);
--ORA-01402: 视图 WITH CHECK OPTIDN where 子句违规
insert into student_view values('107','小胡',25,null);
--可以删除数据,但是如果数据不在where字句范围内,则虽然删除成功,但是并没有影响
--基表中的数据
delete student_view where id='101';
with read only
设置后视图为只读,即不能通过视图对基表中的数据进行删除修改操作
例子: create or replace view student_view
as select * from student with read only;
select * from student_view; --设置了with read only 则 不能对表中的数据进行修改,删除操作
如:delete from student_view where id= '101' ; 语句
此处会报提醒此处不允许虚拟列,可能是因为 Oracle 10g 的原因, Oracle 11g 会提醒 不能对只读视图进行操作 update student_view set name='张三丰' where id='101'
3.视图的使用
为了数据安全
另一个项目需要访问本项目中的一个表的某些字段,为了提高表中数据安全,创建一个视图
视图可以选择性的显示表中的字段和行,因此,视图可以起到隐藏数据,从而保护数据的作用
为了减少代码
一个SQL语句很长,涉及多个表,将它创建为一个视图,可以简化代码
视图可以将复杂的多表连接查询结果构成一个简单的逻辑表,从而提高了获取数据的效率