一、实验目的:
1.掌握创建视图的SQL语句的用法。
2.掌握修改视图的方法。
3.熟悉和掌握对数据表中视图的查询操作和SQL命令的使用;
4.熟悉和掌握对数据表中视图的更新操作和SQL命令的使用,并注意视图更新与基本表更新的区别与联系
5.学习灵活熟练的进行视图的操作,认识视图的作用
二、实验环境:
三、实验内容:
(写出主要的内容)
Part 1 定义视图
在数据库中,以Student Course 和sc 表为基础完成以下视图定义:
create view V_computer
as
select *
from Student
where sdept='CS'
create view V_S_C_G
as
select SC.sno,sname,SC.cno,cname,grade
from Student,Course,SC
where SC.cno=Course.cno and SC.sno=Student.sno
3. 将各系学生人数,平均年龄定义为视图V_NUM_AVG
create view V_NUM_AVG(dno,sums,asage)
as
select sdept,count(*),avg(sage)
from student
group by sdept
4.将各位学生选修课程的门数及平均成绩定义为视图V_AVG_S_G
create view V_AVG_S_G(sno,sums,agrade)
as
select sno,count(*),avg(grade)
from SC
group by sno
5. 各门课程的选修人数及平均成绩定义为视图V_AVG_C_G
create view V_AVG_C_G(cno,cname,sums,agrade)
as
select cno,cname,count(*),avg(grade)
from V_S_C_G
group by cno,cname
Part 2 使用视图
查询以上所建的视图结果。
Select *
from V_Computer
(其它视图V_S_C_G, V_NUM_AVG, V_YEAR, V_AVG_S_G, V_AVG_C_G的查询方法类似)
Select *
from V_S_C_G
Select *
from V_NUM_AVG
Select *
from V_AVG_S_G
Select *
from V_AVG_C_G
查询平均成绩为90分以上的学生学号、姓名和成绩;
参考SQL语句:
Select distinct V_AVG_S_G .sno, V_S_C_G .sname,ascore
From V_AVG_S_G, V_S_C_G
Where V_S_C_G.sno = V_AVG_S_G .sno and ascore > 90;
Select distinct V_AVG_S_G.sno,V_S_C_G.sname,agrade
from V_AVG_S_G,V_S_C_G
where V_S_C_G.sno=V_AVG_S_G.sno and agrade>90;
查询各课成绩均大于平均成绩的学生学号、姓名、课程和成绩;
create view V_AVG
as
select SC.Cno,avg(Grade) AvgGrade
from C,SC
where C.Cno=SC.Cno
group by SC.Cno;
select
distinct S.Sno,Sname,C.Cno,Grade
from S,SC,C,V_AVG
where S.Sno=SC.Sno and C.Cno=V_AVG.Cno and Grade >V_AVG.AvgGrade ;
答:
create view V_AVG
as
select SC.Cno,avg(Grade) AvgGrade
from Course,SC
where Course.Cno=SC.Cno
group by SC.Cno;
select
distinct Student.Sno,Sname,sc.Cno,Grade
from Student,SC,V_AVG
where Student.Sno=SC.Sno and sc.cno=V_AVG.Cno and Grade >V_AVG.AvgGrade ;
按系统计各系平均成绩在80分以上的人数,结果按降序排列;
select distinct student.dno,count(*)sum
from student,V_AVG_S_G
where student.sno=V_AVG_S_G.sno and ascore>80
group by dno
order by sum desc;
Part3 修改视图
1. 通过视图V_Computer,将学号为“201215121”的学生姓名进行修改,并查询结果;
update V_Computer
set Sname='John'
where Sno='201215121';
select *
from V_Computer ;
Select * from student;
2. 通过视图V_Computer,新增加一个学生记录 ('201215201','YAN XI',19,'IS'),并查询结果
insert into V_Computer(Sno,Sname,Sage,Sdept) values('201215201','YAN XI',19,'IS');
select *
from V_Computer ;
Select * from student;
3. 通过视图V_Computer,新增加一个学生记录 ('201215301','Yangyang',20,'MA'),并查询结果
insert into V_Computer(Sno,Sname,Sage,Sdept)
values('201215301','Yangyang',20,'MA');
select *
from V_Computer ;
Select *
From student;
4. 要通过视图V_S_C_G,将学号为“201215127”的姓名改为“Weiwen”,是否可以实现?并说明原因
update V_S_C_G
set Sname='Weiwen'
where Sno='201215127';
select *
from V_S_C_G ;
Select * from student;
5. 要通过视图V_AVG_S_G,将学号为“201215121”的平均成绩改为90分,是否可以实现?并说明原因
不能,因为其包含派生域或常量域。