视图
视图是虚拟的表,只包含使用动态检索数据的查询。
利用视图可以一次性的编写基础SQL,然后根据需要多此调用。
Access不支持视图,MYSQL 5 以后版本支持视图,SQLite只支持只读视图。
视图的作用
- 简化复杂的SQL操作,重用SQL语句。
- 使用表的一部分,而不是使用整个表。
- 保护数据,可以授予用户访问表的特定部分的权限,而不是整个表的访问权限。
- 更改显示的数据格式和表示,视图可以返回与底层表的表示格式不同的数据(如重新进行排序)
视图的规则和限制
- 视图不能重名;对于可以创建的视图数目没有限制
- 创建视图需要权限;视图可以锲套,但不能创建索引
- 视图可以视为基本表,联结的操作对视图均适用。
- 尽量不要从视图中删除或者增添数据,可能会产生严重的后果。
创建视图
使用CREATE VIEW创建视图。
本次使用的关系图
根据where的限制条件创建view
create view product_customer as
select cust_name,cust_contact,prod_id
from customers,orderitems,orders
where customers.cust_id = orders.cust_id
and orderitems.order_num = orders.order_num;
视图创建完毕,查询下测试。
select * from product_customer;
/*
Village Toys John Smith BR01
Village Toys John Smith BR03
Village Toys John Smith BNBG01
Village Toys John Smith BNBG02
Village Toys John Smith BNBG03
Fun4All Jim Jones BR01
......
*/
删除视图
drop view view_name;即可删除视图
用视图过滤数据
-- 创建视图
create view cust_mail_list as
select cust_id,cust_name,cust_email
from customers
where cust_email is not null;
-- 查询结果
select * from cust_mail_list;
/*
1000000001 Village Toys sales@villagetoys.com
1000000003 Fun4All jjones@fun4all.com
1000000004 Fun4All dstephens@fun4all.com
*/
用视图添加计算字段
create view order_item_expanded as
select order_num,prod_id,quantity,item_price,
-- 此处为计算字段
quantity*item_price as expand_price
from orderitems;
select * from order_item_expanded;
/*
20005 BR01 100 5.49 549.00
20005 BR03 100 10.99 1099.00
20006 BR01 20 5.99 119.80
20006 BR02 10 8.99 89.90
20006 BR03 10 11.99 119.90
*/