首先,建立student1,sc,course表,如图
表 Student1
表 sc
表course
alter table sc add constraints fk_sno foreign key(sno) references studnet1(sno)#外键限制
查询以数据处理为先修课程的所有课程。
select * from course where cpno=(select cno from course where cname='数据处理')
查询与张立在同一个系的所有学生姓名。
select * from student1 where sdept=(select sdept from studnet1 where sname='张立' )
查询考试时间在2007-4-20至4-24日之间的参考学生姓名。
select sname,testtime from sc where studnet1.sno=sc.sno and testtime between to_date('2007-4-20','yyyy-mm-dd') and to_date('2007-4-24','yyyy-mm-dd') #一定要把类型转化为date型
查询所有学生参加考试的情况,按照课程划分,输出学生姓名、课程名称、考试时间及成绩。
select student1.cname,course.cname,testtime,grade from student1,sc,course where studnet1.sno=sc.sno and sc.cno=course,cno order by course
查询每门课程考试成绩最高的学生姓名,输出学生姓名、课程名称、成绩、课程学分,按照课程的学分数升序排列。
select max(sname),cname,max(grade),max(credit) from sc,studnet1,sc ,course where studnet1.sno=sc.sno and sc.cno=course.cno group by cname order by max(credit)
#GROUP BY 1.ORDER BY 必须放在group by后面
2.group by 后面的属性必须是前面出现的所有属性(分组函数可以不出现),所以为了合理分组,我们把sname变成了分组函数max(sname) 以此类推
查询参加考试的学生所有课程的总成绩,输出学生姓名、参加考试课程数量、总成绩。
select sname,count(cno),sum(grade) from studnet1,sc where studnet1.sno=sc.sno group by sname
查询参加了三次以上的学生姓名 需用子查询和联接两种方式实现
1.select sname,count(cno) from student1,sc where student1.sno=sc.sno having count(cno)>=3
2.select sname,count(cno) from student1,sc join sc on student1.sno=sc.sno having count(cno)>=3
查询参加过考试的每个学生考的最好的那次考试的情况 用子查询实现
select max(grade),sname,max(cname) from student1,sc,course where student1.sno=sc.sno and course.cno=sc.cno group by sname
alter table sc add constraints