SQL语法整理(五)-视图

视图

含义:从数据库一个或多个表中导出的虚拟表
作用:
方便用户操作: 要求所见即所需,无需添加额外的查询条件,直接查看

增加数据的安全性:通过视图,用户只能查看或修改指定的数据

提高表的独立逻辑性:原有数据表结构的变化,不会影响视图,如果修改原有列,则只需修改视图即可。

  • 创建视图

语法:

MYSQL
create
[algorithm = {undefined | merge | temptable}]
view 视图名[{属性清单}]
as select 语句
[with [cascaded|local] check option];
algorithm:选择的算法
with check option:表示更新视图时要保证在该视图的权限范围之内

undfined:表示MySQL 自动选择所需使用的算法
merge:表示将视图的语句与视图的定义合并,使得视图定义的某一部分取代语句的对应部分
temptable:将视图的结果存入临时表

cascaded:表示更新视图时要满足所有相关视图和表的条件
local:表示更新视图时,要满足该视图本身的定义的条件即可

Mssql
create
view 视图名 as select 语句;

是否有权限创建?(mysql)
通过SQL 查询:
select select_priv,create_view_priv from mysql.user where user = ‘root’;

创建视图

在单表上创建视图:

eg:
create view department_view1 as select * from department;
create view department_view2(name) as select d_name from department;

在多表上创建视图

create algorithm = merge view
employee_view1(name,department,sex,age,address)
as  select name,dept.d_name,sex,age,address
from employee emp inner join department dept on emp.e_no = dept.e_no
with local check option;

查看视图(mysql)

desc 查看

eg: 
desc department_view1;

查看视图 (mssql)

sp_helptext查看

eg: 
exec sp_helptext department_view1;

在sysobjects表中查看(状态)

eg: 
select * from sysobjects where name = 'enployee_view1'

查看视图(Oracle)
在user_views 表中查看(定义)

eg: 
select view_name,text from user_views where view_name = upper('vm_employee');

修改视图

通过create or replace view 修改(mysql)
没有则创建,有则修改

eg: 
create or replace algorithm = temptable
view department_view1(department)
as select d_name from department;

通过alter 修改
只能修改不能创建

eg: 
alter view department_view2(department) 
as select d_name
from department dept
with check option;
  • 更新视图
eg: 
update department_view3 set name ='研发部'

注:更新视图实际上是更新表;并非所有的视图都能更新;

视图不能更新情况:
视图中包含聚合函数

eg: 
create view employee_view4(name) 
as select name,sex,count(name) from employee;

视图中包含union、union all、distinct、group by和having等关键字

eg: 
create view employee_view5(name,sex,address)
as select name,sex,address from employee group by e_np;

常量视图

eg:
 create view employee_view6
as select 'Boyce' as name;

视图中的select 中包含子查询

eg: 
create view employee_view7(name) 
as select (select name from employee);

由不可更新的视图导出的视图(mysql)

eg: 
create view employee_view8
as select * from employee_view7;

创建视图时,algorithm 为temptable 类型(mysql)

eg: 
create algorithm = temptable
view employee_view9
as select * from employee;

视图对应的表上存在没有默认值的列,而且该列没有包含在视图里。[最好视图仅限于查询,若要更新则要考虑全面,否则会造成更新失败]

  • 删除视图

语法:
drop view [if exists] 视图列表

eg: 
drop view if exists employee_view1;
drop view if exists department_view1,department_view2;

判断用户是否有权限:

eg: 
select drop_priv from mysql.user where user = 'root';

---------------------如有错误欢迎指证-------------------------------

你可能感兴趣的:(数据库,数据库,sql,mysql)