mysql 视图

2019-05-07  本文已影响0人  阿啦啦啦啦啦

使用视图的好处

创建视图

# algorithm 视图的算法
# merge是智能合并语句, temptable是把查出来的数据存表,二次再查
# create view v1 as select * from table_1 where a>0
# create view v2 as select * from v1 where a<3
# select * from v1 where a<3 and a>0
create [algorithm={undefined|merge|temptable}] view view_name
as select 列名 from 表名
[with [cascaded|local] check option] 
# 创建或修改视图
create or replace [algorithm={undefined|merge|temptable}] view view_name [(属性清单)] as select语句 [with [cascaded|local] check option];
# 修改视图
alter view view_name as select * from table_1 with local check option;
# 删除视图
drop view if exists view_name;
# 查看视图 
show tables;


algorithm=undefined|merge|temptable 的区别

temptable模式可能会有性能问题

比如查询某用户的评论数

create view comment as select user_id,count(*) as count from table_comment group by user_id
# 由于使用了count统计函数,algorithm会自动解析成temptable算法
# 查询user_id为90的用户评论数量
# 下面这个查询就会扫描整个表结构
select * from comment where user_id=90;



#这个语句的优化过程
#  转换一
select * form (select user_id,count(*) as count from table_comment group by user_id) as comment where user_id=90;
#  转换二
select * form (select user_id,count(*) as count from table_comment group by user_id having  user_id=90) ;
#  转换三,having 提升
select user_id,count(*) as count from table_comment where user_id=90 group by user_id
# 转换四,去掉多余的 group by
select user_id,count(*) as count from table_comment where user_id=90

mysql 不会做这四步优化

local与cascaded的区别

视图 条件 with [cascaded|local] check option
A >80 with local check option
B <90 with local check option
C <90 with cascaded check option

B与C都基于视图A进行查询
(local)更新视图Bset 成绩=70,不会报错,因为70<90,可以更新到数据
(cascaded)更新视图Cset 成绩=70,会报错,因为70<90,但是70不>80

上一篇 下一篇

猜你喜欢

热点阅读