4.2.2 SQL查询中使用视图
视图和关系的用法一样
一旦定义了一个视图,我们就可以用视图名指代该视图生成的虚关系。
使用视图physics_fall_2009
,我们可以用下面的查询找到所有于2009
年秋季学期在Watson
大楼开设的Physics
课程:1
2
3select course_id
from physics_fall_2009
where building = 'Watson';1
2
3
4
5
6
7
8
9mysql> select course_id
from physics_fall_2009
where building = 'Watson';
+-----------+
| course_id |
+-----------+
| PHY-101 |
+-----------+
1 row in set (0.03 sec)
在查询中,视图名可以出现在关系名可以出现的任何地方。
定义视图时指定视图的属性名
视图的属性名可以按下述方式显式指定:1
2
3
4
5
6create view
departments_total_salary(dept_name, total_salary)
as
select dept_name, sum(salary)
from instructor
group by dept_name;
上述视图给出了每个系中所有教师的工资总和。因为表达式sum(salary)
没有名称,其属性名total_salary
是在视图定义中显式指定的。
视图关系的结果通过计算产生
直觉上,在任何给定时刻,视图关系中的元组集是该时刻视图定义中的查询表达式的计算结果因此,如果一个视图关系被计算并存储,一旦用于定义该视图的关系被修改,视图就会过期。为了避免这一点,视图通常这样来实现:当我们定义一个视图时,数据库系统存储视图的定义本身,而不存储定义该视图的查询表达式的执行结果。一旦视图关系出现在查询中,它就被已存储的查询表达式代替。因此,无论我们何时执行这个查询,视图关系都被重新计算。
一个视图可能被用到定义另一个视图的表达式中
例如,我们可以如下定义视图physics_fall_2009_watson
,它列出了于2009
年秋季学期在Watson
大楼开设的所有Physics
课程的标识和房间号:1
2
3
4
5create view physics_fall_2009_watson
as
select course_id,room_number
from physics_fall_2009
where building ='Watson';
其中physics_fall_2009
本身是一个视图关系.
等价视图
这个physics_fall_2009_watson
视图等价于:1
2
3
4
5
6
7
8
9
10
11
12create view physics_fall_2009_watson2
as(
select course_id,room_number
from(
select course.course_id,building,room_number
from course,section
where course.course_id=section.course_id
and course.dept_name = 'Physics'
and section.semester='Fall'
and section.year =2009
) as T where building = 'Watson'
);1
2
3
4
5
6
7mysql> select * from physics_fall_2009_watson2;
+-----------+-------------+
| course_id | room_number |
+-----------+-------------+
| PHY-101 | 100 |
+-----------+-------------+
1 row in set (0.03 sec)1
2
3
4
5
6
7mysql> select * from physics_fall_2009_watson;
+-----------+-------------+
| course_id | room_number |
+-----------+-------------+
| PHY-101 | 100 |
+-----------+-------------+
1 row in set (0.03 sec)