11.视图
11.1 什么是视图
视图view是一张虚拟表,它不存储数据,数据仍在表里,视图由一条查询表的select语句创建,视图只存储select语句。
可以将复杂的查询语句封装成视图,用户可以从视图中查询,以简化SQL编写;
视图中的数据只能查看,不能增删改,可用于权限管理;
屏蔽底层数据结构,对表的部分修改(新增列,修改列类型等)不影响视图的结构,不会对用户和应用程序产生影响。
11.2 视图操作
11.2.1 创建或者修改视图
创建视图语法:
create or replace [ALGORITHM={UNDEFINED|MERGE|TEMPTABLE}]
view view_name [(column_list)]
as select_statement
[WITH [CASCADED|LOCAL] CHECK OPTION]
修改视图语法:
alter [ALGORITHM={UNDEFINED|MERGE|TEMPTABLE}]
view view_name [(column_list)]
as select_statement
[WITH [CASCADED|LOCAL] CHECK OPTION]
说明:
创建视图需要create view权限和drop view权限;
MySQL视图定义中From后不能使用子查询;
[WITH [CASCADED|LOCAL] CHECK OPTION] 指将视图数据更新为不满足视图条件时的设置;
LOCAL只要满足本视图的条件就可以更新;
CASCADED必须满足所有针对该视图的所有视图的条件才可以更新,默认CASCADED。
视图更新限制,含有下列关键字的视图不能做增删改:
聚合函数(sumavgmaxmincount),去重distinct,分组group by ...having,合并union/union all;
常量视图;
连接join或子查询;
from一个不能更新的视图;
where子句的子查询引用了from子句中的表。
例子1:测试[WITH [CASCADED|LOCAL] CHECK OPTION]对视图更新的限制
create or replace view vw_emp as select * from emp where sal<3000;
create or replace view vw_emp_1 as select * from vw_emp where sal>1500 WITH LOCAL CHECK OPTION;
create or replace view vw_emp_2 as select * from vw_emp where sal>1500 WITH CASCADED CHECK OPTION;
select * from vw_emp_1;
select * from vw_emp_2;
update vw_emp_1 set sal=sal+1000 where empno=7566; -- ok
update vw_emp_2 set sal=sal+1000 where empno=7698; -- rror Code: 1369. CHECK OPTION failed 'scott.vw_emp_2'
例子2:不能做增删改的视图
create or replace view vw_emp_dname as select *,(select dname from dept where deptno=emp.deptno) dname from emp;
create or replace view vw_emp_dept as select emp.*,dname,loc from emp,dept where emp.deptno=dept.deptno;
11.2.2 删除视图
删除视图语法:
drop view [if exists] view_name,... [RESTRICT|CASCADE];
说明:
删除视图需要drop view权限;
例子:
drop view vw_emp_2;
11.2.3 查看视图
show tables; -- 既可以查看表,也可以查看视图。
show table status [from db_name] [like 'view_name']; -- 查看视图详细的状态信息
show create view view_name; -- 查看视图的定义
批量查看视图,则可以通过数据字典information_schema.views
select * from information_schema.views;
例子:
show table status like 'vw_emp_dept';
show create view vw_emp_dept;
-- 'CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vw_emp_dept` AS select `emp`.`EMPNO` AS `EMPNO`,`emp`.`ENAME` AS `ENAME`,`emp`.`JOB` AS `JOB`,`emp`.`MGR` AS `MGR`,`emp`.`HIREDATE` AS `HIREDATE`,`emp`.`SAL` AS `SAL`,`emp`.`COMM` AS `COMM`,`emp`.`DEPTNO` AS `DEPTNO`,`dept`.`DNAME` AS `dname`,`dept`.`LOC` AS `loc` from (`emp` join `dept`) where (`emp`.`DEPTNO` = `dept`.`DEPTNO`)'
select * from information_schema.views where table_schema='scott';
11.3 小结