数据库SQL(二):View(视图)详细

文章目录

        • 1、Definition
          • 1)视图产生的原因
          • 2)定义
          • 3)视图和普通查询的区别
        • 2、Example
        • 3、Materialized Views(物化视图)
        • 4、更新视图
        • 5、更新视图的原则(约束)

1、Definition

1)视图产生的原因

In some cases, it is not desirable for all users to see the entire logical model (that is, all the actual relations stored in the database.).A view provides a mechanism to hide certain data from the view of certain users.

也就是说,视图是对数据库中逻辑关系的一层封装,隐藏了原始数据库中的一些内容。视图提供了一种可以隐藏特定数据的机制。

2)定义

Any relation that is not of the logical model but is made visible to a user as a “virtual relation” is called a view.

也就是说,所有用户见到的,但不是最原始的逻辑模型,称之为视图,视图不是真正的逻辑模型,也就是说,视图不会在数据库中新建一张表。
补充说明相关术语:
逻辑模型:逻辑模型指的是数据库中数据之间的关系,通俗理解,就是数据表,将一张表称为一个逻辑关系。
物理模型:数据库中数据在磁盘中真实存在的位置关系,比如某个数据在哪个磁道,哪个盘面,哪个扇区。
在下文中,将会以逻辑关系表示数据表。

3)视图和普通查询的区别
  • 视图得到的解雇不是一种逻辑模型,普通查询是。
  • 视图的结果能查,但只能做有限制的修改,普通查询就是增删改查。
  • 视图相当于是普通逻辑模型之上的一层封装。

2、Example

  • 视图的创建语法:
    create view v as < query expression >
    where is any legal SQL expression. The view name is represented by v.
    此处创建了一个 faculty视图。
    在这里插入图片描述
  • 视图的创建可以依赖其他视图
    视图physics_fall_2009_waston是在视图physics_fall_2009_基础上创建的
    在这里插入图片描述

3、Materialized Views(物化视图)

前面提过,视图本身不会创建逻辑模型,也就是说,如果视图中需要查询的数据,在原逻辑模型中更新了,那么视图的结果也是会随之更新的,但有一种视图例外,那就是物化视图。

物化视图和视图类似,反映的是某个查询的结果,但是和视图仅保存SQL定义不同,物化视图本身会存储逻辑关系,因此是物化了的视图。

优势:
频繁使用物化视图的应用,因为存储了视图关系,可以提高响应熟读。比如:一些基于聚合函数做统计计算查询的应用,可以定义有关聚合函数计算的物化视图,在物化视图上查询要快很多,避免读取规模大的实际关系表。常用于查询业务量较大的应用。

缺点:
If relations used in the query are updated, the materialized view result becomes out of date

因此,当原数据更新时,物化视图不会随之更新,如果需要看到最新的结果,需要手动更新。

4、更新视图

在这里插入图片描述
This insertion must be represented by the insertion of the tuple
(’30765’, ’Green’, ’Music’, null)
into the instructor relation.

因此,对视图faculty操作,相当于是对instructor逻辑关系操作。

5、更新视图的原则(约束)

参考以下更新视图,是错误的例子
在这里插入图片描述
which department, if multiple departments in Taylor?
what if no department is in Taylor?
数据库并不能推导出新插入的关系该如何插入到instructor 和department中,因此错误。

所以,对于视图的插入有以下几种约束:

  • The from clause has only one database relation.
  • The select clause contains only attribute names of the relation, and does not have any expressions, aggregates, or distinct specification.
  • Any attribute not listed in the select clause can be set to null
  • The query does not have a group by or having clause.

也就是说,当且仅当,来自一张表,并且视图中select的内容没有任何聚会函数、表达式,以及没有出现在视图中的属性可以为空,并没有使用group by也没有约束。简而言之,就是视图的查询要简单,尽可能的简单,才能做更新。