1、查询"001"课程比"002"课程成绩高的学生的信息及课程分数
思路:同表多次查询
select s.*,s1.score from student s,sc s1,sc s2
where s1.cid='001' and s2.cid='002'
and s.sid=s1.sid
and s1.sid=s2.sid
and s1.score>s2.score
或
select s.*,s1.score from student s,
(select sid, score from sc where cid='001') s1,
(select sid,score from sc where cid='002') s2
where s1.score>s2.score
and s.sid=s1.sid
and s1.sid=s2.sid
注:第二种方法虽然繁琐但是对日后的多表子查询有所帮助
2.查询"001"课程比"002"课程成绩低的学生的信息及课程分数且不存在"001"课程但存在"002"课程
思路:不存在001但存在002 右链接,同样,sc表多次查询
select s.*,s2.score from student s,
(select sid,score from sc
where cid='001') s1
right join
(select sid,score from sc
where cid='002') s2
on s1.sid=s2.sid
where s.sid=s2.sid
3.查询平均成绩小于60分的同学的学生编号和学生姓名和平均成绩且包含不存在成绩的学生信息的SQL语句
思路:avg() groupby.... having ...以及nvl()函数
select s.sid,s.sname,a.avg1 from student s,
(select sid,round(avg(score)) as avg1 from sc
group by sid
having nvl(round(avg(score)),0)<60
) a
where a.sid=s.sid
注:round()函数为取四舍五入后的整数,具体格式可自行查询
avg(),sum(),count()等聚合函数后面一定要group by having是对分组的条件
4.查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩
思路:选课总数用count(),总成绩用sum()
select s.sid,s.sname,a.count1 as 选课总数,a.sum1 as 课程总成绩 from student s,
(select sid,count(cid) as count1,sum(score) as sum1 from sc
group by sid
) a
where a.sid=s.sid
5.查询"叶"姓老师的数量
select count(tname) from teacher
where tname like '叶%'
6.查询学过"叶平"老师课的同学的信息
思路 "叶平"--tid-cid--sid--student表
select distinct s.* from student s,course,teacher,sc
where s.sid=sc.sid
and teacher.tid=course.tid
and course.cid=sc.cid
and teacher.tname='叶平'
7.查询没学过"叶平"老师课的同学的信息
思路 :上一题直接嵌套 not in
select s.* from student s where sid not in
(select s1.sid from student s1,course,teacher,sc
where s1.sid=sc.sid
and teacher.tid=course.tid
and course.cid=sc.cid
and teacher.tname='叶平')
8.查询学过编号为"001"并且也学过编号为"002"的课程的同学的信息
思路:先查询学过001课程的学号再查询学过002课程的学号最后三表连接
select s.* from student s ,
(select sid from sc
where cid='001'
) a,
(select sid from sc
where cid='002'
) b
where a.sid=b.sid
and s.sid=a.sid
9.查询学过编号为"001"但是没有学过编号为"002"的课程的同学的信息
select s.* from student s ,
(select sid from sc
where cid='001'
and sid not in
(select sid from sc
where cid='002')
) a
where s.sid=a.sid
10.查询没有学全所有课程的同学的信息
思路:count(cid) group by sid select s.* from student s ,
(select sid,count(cid) from sc
group by sid
having count(cid)<(select count(cid) from course)
) a
where a.sid=s.sid