一、实验目的
1.掌握Management Studio的使用。
2.掌握SQL中连接查询和嵌套查询的使用。
二、实验内容及要求(请同学们尝试每道题均使用连接和嵌套两种方式来进行查询,如果可以的话)
1. 找出所有任教“数据库”的教师的姓名。
连接查询:
select distinct t.Teac_name
from teacher t
join courseteacher st on t.teac_id=st.teac_id
join course c on st.course_id=c.course_id
where c.course_name='数据库'
嵌套查询:
select distinct Teac_name
from teacher
where teac_id in
(select teac_id
from courseteacher
where course_id in
(select course_id
from course
where course_name='数据库'))
2. 取出学号为“980101011”的学生选修的课程号和课程名。
嵌套查询:
select course_id ,course_name
from course
where course_id in
(select course_id
from studentgrade
where stu_id='980101011')
连接查询:
select c.course_id ,c.course_name
from course c
join studentgrade sg on c.course_id=sg.course_id
where sg.stu_id='980101011'
3.“涂杰杰”所选修的全部课程号及成绩。(注意:school中有同名,即有两名学生叫“涂杰杰”。)
select stu_id
from student
where stu_name='涂杰杰'
连接查询:
select st.course_id,st.grade
from studentgrade st
join student s on s.stu_id=st.stu_id
where s.stu_name='涂杰杰' and s.stu_id='980101003'
嵌套查询:
select course_id,grade
from studentgrade
where stu_id in
(select stu_id
from student
where stu_name='涂杰杰' and stu_id='980101003')
4.找出“苏贤兴”同学所学课程的名称和成绩。(请使用连接查询和嵌套查询分别来完成)
连接查询
select course_name,grade
from student,course,studentgrade
where stu_name='苏贤兴' and student.stu_id=studentgrade.stu_id
and course.course_id=studentgrade.course_id
嵌套查询
select course_name,grade
from course,studentgrade
where course.course_id=studentgrade.course_id
and stu_id in(select stu_id
from student
where stu_name='苏贤兴')
5.显示所有课程的选修情况(外连接)。
select course.course_id,course_name,stu_id,grade
from course
left outer join studentgrade on (course.course_id=studentgrade.course_id)
6.检索选修课程号为“0109”或“0111”的学生学号、姓名和所在班级。
select s.stu_id,stu_name,class_id
from student s,course c,studentgrade sg
where c.course_id='0109' or c.course_id= '0111'
and s.stu_id=sg.stu_id
and c.course_id=sg.course_id
7.查询“0203”课程的最高分的学生的学号。
--方法一
select stu_id
from studentgrade
where grade=
(select max(grade)
from studentgrade
where course_id='0203')
--方法二
select top 1 stu_id
from studentgrade
where course_id='0203'
order by grade desc
8.没有选修以“01”开头的课程的学生信息。(用子查询完成,提示not in或not exists。需考虑没选课的学生)
--方法一
select stu_id,stu_name
from student
where stu_id not in
(select stu_id
from studentgrade
where course_id like '01%')
--方法二
select stu_id,stu_name
from student
where not exists
(select *
from studentgrade
where course_id like '01%' and student.stu_id=studentgrade.stu_id)
三、实验小结
1.思考简单查询、连接查询与嵌套查询有什么不同?连接查询与嵌套查询有何区别与联系?
2.此次实验中得到的哪些经验教训、疑难问题?有什么心得或总结?