Skip to content

Commit

Permalink
update sql docs
Browse files Browse the repository at this point in the history
  • Loading branch information
fengzhao committed Jul 17, 2024
1 parent 80ff9a4 commit 9ba00ac
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions docs/basic/5.relation.md
Original file line number Diff line number Diff line change
Expand Up @@ -568,3 +568,48 @@ SQL允许通过查询来定义“虚关系”。它在概念上包含查询的
(4)视图能够对机密数据提供安全保护。在用户查询数据库的数据时,只提供必要的数据视图,防止未经许可的用户访问敏感数据。


```SQL
-- 视图的定义,其中 query expression 是任意合法的查询表达式
create view view_name(column1,column2 ...) as <query expression>


-- 列出Physics系在2009年秋季学期开设的所有课程段
create view physics_fall_2009 as
select course, course_id, sec_id, building, room_number
from course, section
where course.course_id = section.course_id
and course.dept_name = 'Physics'
and course.semester = 'Fall'
and course.year = '2009'



-- 物化视图(Materialization VIEW)
-- 由于视图中的数据是从表中查询出来的,所以一旦表中的数据发生改变,视图就会过期,所以视图中的数据也要发生改变。
-- 这样的视图称为物化视图(materialized view)

-- 物化视图维护(materialized view maintenance)
-- 保持视图物化一直在最新状态的过程称为物化视图维护,物化视图维护的策略大概有几种:
-- 1. 每当数据变更时就进行视图物化
-- 2. 周期性的进行视图物化
-- 3. 当需要访问视图时才进行视图物化


-- 当定义视图的时候,一般来说数据库只会存储该视图定义的查询语句。与此相反,物化视图是一个其内容已计算并存储的视图。
-- 物化视图带来了冗余数据,因为其内容可以通过视图定义和表中的数据来查询得到。

-- MySQL的视图不是一种物化视图,它相当于一个虚拟表,它本身并不存储数据,它是作为一个select语句保存在数据字典中的。
-- 通过视图,可以展现基表的部分数据;视图数据来自定义视图的查询中使用的表,使用视图动态生成。
-- 这带来的问题是使用视图并不能将常用数据分离出来,优化查询速度。
-- 且操作视图的很多命令都与普通表一样,这会导致在业务代码中无法通过sql区分表和视图,使代码变得复杂。


-- 实现视图的方式有两种,分别为合并算法和临时表算法

-- 合并算法是指查询视图时将视图定义的sql合并到查询sql中,比如create view v1 as select * from user where sex=m;
-- 当我们要查询视图时,mysql会将select id,name from v1;合并成select id,name from user where sex=m……;

-- 临时表算法是先将视图查出来的数据保存到一个临时表中,查询的时候查这个临时表。不管是合并算法和临时表算法都会带来额外的开销。
-- 且如果使用临时表后会使mysql的优化变得很困难,比如索引。
-- 很多人本末倒置,复杂的SQL语句都是由于数据库表结构设计不合理造成的,不去反思为什么这么设计。
```

0 comments on commit 9ba00ac

Please sign in to comment.