《mysql必知必会》笔记

Mysql语法之使用视图

2019-08-11  本文已影响2人  etron_jay

一、视图

视图是虚拟的表,与包含数据的表不一样,视图只包含使用时动态检索数据的查询

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';

现在假如可以把整个查询包装成一个名为productcustomers的虚拟表:

select cust_name, cust_contact
from productcustomers
where prod_id = 'TNT2';

1.为什么使用视图

在视图创建之后,可以用与表基本相同的方式利用它们。可以对视图执行select操作,过滤和排序操作。

将视图联结到其他视图或表,甚至能添加和更新数据

重要的是知道视图仅仅是用来查看存储在别处的数据的一种设施。

视图本身不包含数据,因此它们返回的数据是从其他表汇总检索出来的。

使用视图的性能可能降低,因为视图不包含数据,所以每次使用视图时,都必须处理查询执行时所需的任一个检索。性能将会下降。

二、使用视图

1.利用视图简化复杂的联结

视图的最常见的应用之一是隐藏复杂的SQL,这通常都会涉及联结。

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;

这条语句创建一个名为productcustomers的视图,它联结三个表,以返回已订购了任意产品的所有客户的列表。

select cust_name, cust_contact
from productcustomers
where prod_id = 'TNT2';

2.用视图重新格式化检索出的数据

select Concat(RTrim(vend_name),'(',RTrim(vend_country),')') AS vend_title
from vendors
order by vend_name
CREATE VIEW vendorlocations AS

select Concat(RTrim(vend_name),'(',RTrim(vend_country),')') AS vend_title
from vendors
order by vend_name
select * 
from vendorlocations;

3.用视图过滤不想要的数据

create view customeremaillist AS
select cust_id, cust_name, cust_email
from customers
where cust_email is not null;
select * 
from customeremaillist;

4.使用视图与计算字段

select prod_id,
    quantity,
    item_price,
    quantity*item_price AS expanded_price
from orderitems
where order_num = 20005;
create view orderitemsexpanded AS

select prod_id,
    quantity,
    item_price,
    quantity*item_price AS expanded_price
from orderitems
where order_num = 20005;
select * from orderitemsexpanded
where order_num = 20005;

5.更新视图

如果视图定义中有以下操作,则不能进行视图的更新:

上一篇 下一篇

猜你喜欢

热点阅读