一、视图
1.1、什么是视图
视图(view)是一种虚拟存在的表,是一个逻辑表,本身并不包含数据。作为一个select 语句保存在数据字典中的。
通过视图,可以展现基表的部分数据;视图数据来自定义视图的查询中使用的表,使用视图动态生成。
基表:用来创建视图的表叫做基表(base table)
1.2、为什么要使用视图
因为视图的诸多优点,如下:
- 简单:使用视图的用户完全不需要关心后面对应的表的结构、关联条件和筛选条件,对用户来说已经是过滤好的复合条件的结果集。
- 安全:使用视图的用户只能访问他们被允许查询的结果集,对表的权限管理并不能限制到某个行某个列,但是通过视图就可以简单的实现。
- 数据独立:一旦视图的结构确定了,可以屏蔽表结构变化对用户的影响,源表增加列对视图没有影响;源表修改列名,则可以通过修改视图来解决,不会造成对访问者的影响。
总而言之,使用视图的大部分情况是为了保障数据安全性,提高查询效率。
1.3、示例
-- 使用sql查询
select cust_name,cust_contact from customers,orders,orderitems
where customers.cust_id=orders.cust_id
and orderitems.order_num=orders.order_num
and prod_id='TNT2';
查询结果
cust_name | cust_contact | |
---|---|---|
1 | Yosemite Place | Y Sam |
2 | Coyote Inc. | Y Lee |
-- 创建视图
create view productcustomers AS
select cust_name,cust_contact,prod_id
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 prod_id