什么是视图
视图是虚拟的表,与包含数据的表不一样,视图只包含使用时的动态检索数据的查询。
理解视图最好的方法无外乎就是通过一个简单易懂的例子:
select cust_name, cust_contrats
from customers, orders, orderitems
where customers.cust_id = orders_cust_id
and orderitems.order_num = orders.order_num
and prod_id = 'TNT2'
这个查询语句用来查询订购了某个特定产品的客户。任何需要这个数据的人都必须理解相关表的结构,并且知道如何创建查询和对表进行联结。为了检索其他产品的相同数据,必须修改最后的 where 子句。
现在,假如可以把整个查询包装成为一个名为 productcustomers 的虚拟表,则可以如下容易的检索出数据:
select cust_name, cust_contract
from productcustomers
where prod_id = 'TNT2'
这个就是试图的作用,productcustomers 是一个视图,作为视图,它不包含表中应该有的任何数据,它包含的是一个 SQL 查询,和上面的联结表查询的作用是一样的。
为什么要用视图
重用 SQL 语句
简化复杂的SQL 操作,在编写查询后,可以方便的重用它而不必知道它的基本查询细节
使用表的组成部分,而不是整个表
有效的保护数据,可以给用户授予表特定部分的访问权限而不是整个表的访问权限
更改数据格式和表示,视图可以返回与底层表格式不一样的数据。
使用视图
创建视图,通过create view name 来创建,以上面 productcustomers为例:
create view productcustomers as
select cust_name, cust_contrats
from customers, orders, orderitems
where customers.cust_id = orders_cust_id
and orderitems.order_num = orders.order_num
使用视图
select cust_name, cust_contact
from productcustomers
where proc_id = 'TNT2'
视图的检索使用跟表没什么区别,可以关键字来处理检索数据,礼物 concat 等,通过where 等关键字来过滤。
视图的 insert 、update、delete 操作:这些操作都是基于表的操作,只要符合表的插入、更新、删除相关操作就可以。
视图的限制和规则
和表的名字一样,视图的名字必须唯一。
对于可以创建的视图的数目没有限制
为了创建视图,必须有足够的访问权限,这些权限由数据库管理员授予
视图可以嵌套,即可以从一个视图的检索结果来构建一个新的视图
视图不能建立索引,不能有关联的触发器或默认值。
视图和表可以组合一起使用,例如,编写一条联结表和视图的 select 语句。