实验目的:
- 熟练掌握SQL Server 查询分析器的使用方法,学会灵活熟练的使用SQL语句的各种形式,加深对SQL语言查询语句的理解;
- 熟悉多表的连接查询与嵌套查询语句的正确写法,加深对嵌套查询和连接查询的理解,比较两种方法的不同。
实验内容:
在 SQL Server软件上,使用关系数据库标准语言SQL,掌握嵌套查询操作和基本的连接查询操作:等值连接、非等值连接、自身连接、外连接。
S(S#,Sname,Sage,Ssex) 学生表
C(C#,Cname,T#) 课程表
SC(S#,C#,score) 选课表
T(T#,Tname) 教师表
实验步骤:
语句实现:
(1) 查询每个学生及其选课情况;
select *from S,SC where S.sno= SC.sno
(2) 将S,SC进行右连接
select * from S right outer join SC on S.sno=SC.sno
(3) 查询既选修了2号课程又选修了3号课程的学生姓名、学号;
select S.Sno,Sn from SC inner join S on S.Sno=SC.Sno and (Cno='11’or Cno=‘12’) group by Sn,S.Sno;
(4) 查询和刘志同一年龄的学生
SELECT S.* from S where sage=(select sage from S where sn=‘刘志’) and sn<>‘刘志’
(5) 选修了课程名为“数据库”的学生姓名和年龄
select s.sn,s.sage from s,sc,c where s.sno=sc.sno and sc.cno=c.cno and cn=‘数据库’
(6) 查询其他系比信息系任一学生年龄小的学生名单
SELECT S.* from S where sage<all(SELECT sage from S where dno =‘2’) and dno <>‘3’
(7) 查询其他系中比信息系所有学生年龄都小的学生名单
SELECT S.* from S where sage<all(SELECT sage from S where dno =‘3’) and dno <>‘2’
(8) 查询选修了2门以上课程的学生姓名
select sno, sn from s where sno in(select sc.sno from sc group by sc.sno having count (*)>=2)
(9) 查询信息系学生及其性别是男的学生
select sn,sex from S where dno=4 and sex=‘男’
(10) 查询选修课程11的学生集合和选修12号课程学生集合的差集
select sno from sc where cno=‘11’ except select sno from sc where cno=‘12’
(11) 查询李思同学不学的课程的课程号
select cno,cn from c where cno not in(select cno from sc where sno=(select sno from s where sn=‘李思’))
(12) 查询选修了13号课程的学生平均年龄
select avg(sage) as avg from S where Mno=13
(13)求年龄大于所有女同学年龄的男同学姓名和年龄
select sn,sage from s where sex=‘男’ and sage>all(select max(sage)from s where sex=‘女’)
实验结论:
(1) 通过这次试验,熟悉了SQL SERVER 工作环境;
(2) 掌握了连接查询(等值和非等值连接,自身连接,外接),嵌套查询(带有in 的子查询,带有比较运算符的子查询),能灵活使用SQL语言命令对表中数据进行连接嵌套查询。为我以后的学习打好基础,积攒了经验。