连接查询:条件可以通过链接谓词链接
【例3.49】查询每个学生及其选修情况
select Student.*,Sc.*
from student,sc
where student.sno=sc.sno;
如果两个表中属性列是唯一的,则可以省略,如果不唯一,比如Student.sno和SC.sno就不可以省略
【例3.51】查询选修了2号课程且成绩在80分以上的所有学生姓名和学号和分数
select Student.Sno,Sname,SC.grade
from Student,Sc
where Student.Sno=Sc.Sno and Sc.Cno='2' and SC.Grade>80;
自身连接:自己与自己连接
【例3.52】查询每一门课的间接先修课
select*
from course;
select second.cno, second.cpno ,first.cpno
from course first,course second
where second.Cpno=first.cno;
外链接,左外链接保留左边关系,右外链接保留右边关系
【例3.53】例3.49题目
select Student.*,Sc.*
from student right outer join sc on (student.sno=SC.sno);
select Student.*,Sc.*
from student left outer join sc on (student.sno=SC.sno);
多表连接:很多表也可以连接
【例3.54】查询每个学生的学号,姓名,选修课名称和成绩
select student.sno,sname,course.cno,sc.grade
from student, sc,course
where student.sno=sc.sno and course.cno=Sc.cno;
嵌套查询:一个子查询块嵌套在一个父查询块
注意:子查询块中不可以使用order by语句
【例3.55】查询和小刘同一个系的学生
首先先找到小刘所在的系:
select sdept
from stdent
where sname='小刘';
结果为CS
再找CS系的学生:
select sname, sno, sdept
from student
where sdept='CS';
两个合起来就是嵌套查询了:
select sname ,sno, sdept
from student
where sdept in
(
select sdept
from student
where sname='小刘');
【例3.56】查询选修了课程名为信息系统的学生的学号和姓名
select sname ,sno
from student
where sno in
(
select sno
from sc
where cno in
(
select cno
from course
where cname='信息系统')
);
【例3.57】查询每个学生超过他课程平均分的课程号
select cno,sno
from sc x
where grade>=
(
select avg(grade)
from sc y
where y.sno=x.sno
);
【例3.58】查询非计算机系中比计算机科学系中任意一个学生年龄小的学生姓名和年龄
select sname,sage
from student
where sage<any
(
select sage
from Student
where Sdept='CS'
)
and Sdept!='CS';