数据库——视图

Part 1 定义视图

在数据库中,以Student Course 和sc 表为基础完成以下视图定义:

1.定义计算机系学生基本情况视图V_Computer;

create view is_student

as

select sno,sname,sage

from student

where sdept='cs'

with check option;

 

2. 将Student Course 和sc表中学生的学号,姓名,课程号,课程名,成绩定义为视图V_S_C_G

create view V_S_G

as

select student.sno,sname,course.cno,cname,sc.grade

from student,course,sc

where student.sno=sc.sno and 

  sc.cno=course.cno

with check option;

 

3. 将各系学生人数,平均年龄定义为视图V_NULL_AVG

create view V_NULL_AVG

as

select count(sno)人数,avg(sage)平均年龄,sdept

from student

group by sdept;

 

 

4. 将各位学生选修课程的门数及平均成绩定义为视图V_AVG_S_G

create view V_AVG_S_G

as

select sc.sno,count(course.cno)课程门数,avg(grade)平均成绩

from student,sc,course

where student.sno=sc.sno and course.cno=sc.cno

group by sc.sno;

 

5. 各门课程的选修人数及平均成绩定义为视图V_AVG_C_G

create view V_AVG_C_G

as

select cno,count(cno)课程选修人数,avg(grade)平均成绩

from sc

group by cno;

 

Part 2 使用视图

查询以上所建的视图结果。

Select *

from is_student

 

其他试图查询方式类似:

 

 

 

 

 (其它视图V_S_C_G, V_NUM_AVG, V_YEAR, V_AVG_S_G, V_AVG_C_G的查询方法类似)

2.查询平均成绩为90分以上的学生学号、姓名和成绩;

select distinct V_S_G.sno,V_S_G.sname,V_AVG_S_G.平均成绩

from V_S_G,V_AVG_S_G

where V_S_G.sno=V_AVG_S_G.sno AND 平均成绩>90;

 

 

3.查询各课成绩均大于平均成绩的学生学号、姓名、课程和成绩;

select sname,student.sno,sc.cno,grade

from student,sc,V_AVG_C_G

where student.sno=sc.sno and sc.cno=V_AVG_C_G.cno and grade>V_AVG_C_G.平均成绩;

 

 

4.按系统计各系平均成绩在80分以上的人数,结果按降序排列;

select distinct student.sdept,count(V_AVG_S_G.sno) as sums

from student,V_AVG_S_G

where student.sno=V_AVG_S_G.sno and 平均成绩>80

group by sdept,平均成绩

order by sums desc;

 

    Part3 修改视图

    1. 通过视图V_Computer,将学号为“201215121”的学生姓名进行修改,并查询结果;

update is_student

set sname='修改的名字'

where sno='201215121';   

 

select *

from is_student;

 

   2. 通过视图V_Computer,新增加一个学生记录 ('201215201','YAN XI',19,'IS'),并查询结果

insert into V_Computer(Sno,Sname,Sage,Sdept) values('201215201','YAN XI',19,'CS');  

select *

from  V_Computer ;

Select * from student;

 

要通过视图V_S_C_G,将学号为“201215127”的姓名改为“Weiwen”,是否可以实现?并说明原因

update V_S_G

set sname='weiwen'

where sno='201215127';

select *

from  V_S_G ;

Select * from student;

 

 

 

4.要通过视图V_AVG_S_G,将学号为“201215121”的平均成绩改为90分,是否可以实现?并说明原

答:不能,对视图或函数'V_AVG_S_G' 的更新或插入失败,因其包含派生域或常量域。

猜你喜欢

转载自blog.csdn.net/hml666888/article/details/80919406