南 京 晓 庄 学 院
《数据库原理与应用》
课程实验报告
实验五 嵌套子查询设计实验
1.实验目的
(1) 掌握多表查询和子查询的方法。
(2) 熟练使用IN、比较符、ANY或ALL和EXISTS操作符进行嵌套查询操作。 (3) 理解不相关子查询和相关子查询的实现方法和过程。
2.实验要求
(1) 针对 “TM”数据库,在SQL Server查询分析器中,用T-SQL语句实现以下查询操作:
a) 查询选修了数据结构与算法的学生学号和姓名。
b) 查询07294002课程的成绩低于孙云禄的学生学号和成绩。
c) d) e) f) g) h) i) j) 查询和孙云禄同年出生的学生的姓名和出生年份。
查询其他系中年龄小于数学与信息技术学院年龄最大者的学生。 查询其他系中比数学与信息技术学院学生年龄都小的学生。
查询同孙云禄数据库原理与应用课程分数相同的学生的学号和姓名。 查询选修了07294002课程的学生姓名。 查询没有选07294002课程的学生姓名。
查询同时选修了07295006和07295007课程的学生的学号。
查询所有未授课的教师的工号、姓名和院系,结果按院系升序排列。
扩展实验:
a) 查询和10060101选修的全部课程相同的学生的学号、课程号、期末考试
成绩。
b) 查询至少选了10060101选修的全部课程的学生的学号。
c) 查询年龄比所在院系平均年龄小的学生的学号、姓名、年龄、院系,按
院系和年龄升序排列。
d) 查询每门课都在80分以上的学生的学号和姓名。
(2) 在SQL Server Management Studio中新建查询,尽可能用多种形式表示实验中的查询语
句,并进行比较。
(3) 按要求完成实验报告。
3.实验步骤、结果和总结实验步骤/结果
将调试成功的T-SQL语句写在下方(标明题号)。
a)查询选修了数据结构与算法的学生学号和姓名。
select Student.S_ID,Student.S_Name from Student,Course,SC
where Student.S_ID=SC.S_ID and Course.C_ID=SC.C_ID and Student.S_ID=SC.S_ID and C_Name='数据结构与算法'
b)查询07294002课程的成绩低于孙云禄的学生学号和成绩
select Student.S_ID,SC.EXAM_Grade from Student,SC
where Student.S_ID=SC.S_ID and SC.EXAM_Grade<(select SC.EXAM_Grade from Student,SC
where Student.S_ID=SC.S_ID and Student.S_Name='孙云禄' and SC.C_ID='07294002')
2
c)查询和孙云禄同年出生的学生的姓名和出生年份。
select S_Name,Date_of_Birth from Student
where Year(Date_of_Birth )=(select year(Date_of_Birth )
from student
where S_Name='孙云禄' )and S_Name !='孙云禄'
d)查询其他系中年龄小于数学与信息技术学院年龄最大者的学生。
select * from Student
where DEPT_ID<>'数学与信息技术学院' and year(getdate())-year(Date_of_Birth)
(select max(year(getdate())-year(Date_of_Birth) ) as 年龄from Student,Department
where Student.DEPT_ID=Department.DEPT_ID and DEPT_Name='数学与信息技术学院')
3
e)查询其他系中比数学与信息技术学院学生年龄都小的学生。
select * from Student
where year(getdate())-year(Date_of_Birth)<(
select min(year(getdate())-year(Date_of_Birth)) as 年龄 from Student,Department
where Student.DEPT_ID=Department.DEPT_ID and DEPT_Name='数学与信息技
术学院')andDEPT_ID<>'07'
f)查询同孙云禄数据库原理与应用课程分数相同的学生的学号和姓名。
select s.s_id,s_name from student s,sc,course c
where s.s_id=sc.s_id and sc.c_id=c.c_id
and c.c_name='数据库原理与应用' and s_name<>'孙云禄' and exam_grade=(
select exam_grade
from student s,sc,course c
where s.s_id=sc.s_id and sc.c_id=c.c_id
and s_name='孙云禄' and c.c_name='数据库原理与应用' )
g)查询选修了07294002课程的学生姓名。
4
select S_Name from Student,SC
where Student.S_ID=SC.S_ID and SC.C_ID='07294002'
h)查询没有选07294002课程的学生姓名。
select S_Name from Student
where S_ID not in(select S_ID from SC where C_ID ='07294002')
i)查询同时选修了07295006和07295007课程的学生的学号。
select a.s_id from sc a,sc b
where a.s_id=b.s_id and a.C_ID ='07295007' and b.c_id='07295006';
j)查询所有未授课的教师的工号、姓名和院系,结果按院系升序排列。
select T_ID,T_NAME,DEPT_ID from Teacher
where T_ID not in(select T_ID from TC ) order by DEPT_ID
5