MySQL视图 view

视图

view可以看成一张虚拟的表,是表通过某种运算得到的一个投影

--查询每个栏目下商品的平均价格,并取平均价前3高或3低的栏目
//结果集频繁用到
select cat_id,avg(shop_price) as avgprice from goods 
group by cat_id order by avgprice DESC limit 3; 

创建视图

--视图只是表的某种查询的投影,主要步骤在于查询表上,查询结果命名为视图就可以
CREATE VIEW 视图名
AS
SELECT 语句 

视图一旦创建完毕,就可以像表一样进行查询 
视图的作用: 
1)可以简化我们的查询 
2)更精细的权限控制 
3)数据多,分表时可以用到 
表的数据变化,要影响到视图的数据的变化;视图某种情况下可以修改的
要求:视图的数据和表的数据一一对应,就像函数的映射 表->推出视图对应的数据, 视图->推出表对应的数据

删除视图

drop view 视图名; 

视图 algorithm

Algorithm = merge/temptable/undefined
Merge 当引用视图时,引用视图的语句与定义视图的语句合并
Temptable 当引用视图时,根据视图的创建语句建立一个临时表
Undefined 未定义,自动,让系统帮你选
Merge意味着视图只是一个规则,语句规则,当查询视图时,把查询视图的语句(比如where那些)与创建的语句where子句等合并,分析形成一条select语句。

--创建视图的语句
create algorithm=merge view g2 as
select goods_id,cat_id,goods_name,shop_price from goods
where shop_price >2000
--查询视图的语句
select * from g2 where shop_price <3000;
--最终执行的语句:
select goods_id,cat,goods_name,shop_price from goods
where shop_price > 2000 and shop_price <3000; 

而temptable是根据创建语句瞬间创建一张临时表,然后查询视图的语句从该临时表查数据

create algorithm=temptable view g2 as
select goods_id,cat_id,goods_name,shop_price from goods
where shop_price > 2000
--查询视图的语句:
select * from g2 where shop_price < 3000; 

 

posted on 2015-06-27 12:55  gimin  阅读(152)  评论(0)    收藏  举报