20.视图

(一)视图的介绍

视图:MySql从5.0.1版本开始提供视图功能。一种虚拟存在的表,行和列的数据来自定义视图的查询中使用的表,并且是在使用视图时动态生成的,只保存了sql逻辑,不保存查询结果。

应用场景:

1.多个地方用到同样的查询结果。

2.该查询结果使用的sql语句较复杂。

(二)视图的创建

语法:

create view 视图名

as

查询语句;

(三)视图的优点

1.重用sql语句。

2.简化复杂的sql操作,不必知道它的查询细节。

3.保护数据,提高安全性。

(四)视图的修改

1)方式一

create or replace view 视图名

as

查询语句;

存在就修改,不存在就创建。

2)方式二

alter view 视图名

as

查询语句;

(五)视图的删除

语法:

drop view 视图名,视图名,...;

(六)查看视图结构

desc 视图名;

show create view 视图名;

(七)视图的更改

1.插入insert

2.修改update

3.删除delete

注意:会更改原始表。

但具备以下特点的视图不允许更新:

1)包含以下关键字的sql语句:分组函数、distinct、group by、having、union或union all。

2)常量视图。

3)select中包含子查询。

create or replace view myv3
as
select(select max(salary) from employees);

4)select中包含join。

5)from一个不能更新的视图

6)where子句的子查询引用了from子句中的表。

create or replace view myv6
as 
select last_name,email,salary
from employees
where employee_id in(
    select manager_id
    from employees
    where manager_id is not null
);
发布了90 篇原创文章 · 获赞 48 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Asher_S/article/details/89600656
今日推荐