多表连接查询
#(1) 查询选修了【数据库原理】的计算机系的学生学号和姓名。
select student.sno,sname,cname
from student,courses,sc
where
student.sno = sc.sno and courses.cno=sc.cno and cname='数据库原理'
#(2) 查询每一门课的间接先行课(即先行课的先行课),显示课程编号和该门课程的间接先行课编号。
select c1.cno,c2.precno
from courses c1 left join courses c2
ON c1.precno=c2.cno
where c2.precno is not null
#(3) 查询学生的学号、姓名、选修课程的名称和成绩。
select student.sno,sname,cname,grade
from student,sc,courses
where student.sno=sc.sno and sc.cno=courses.cno
#(4) 查询选修了课程的学生姓名。
select DISTINCT sname
from student,sc
where student.sno=sc.sno;
或者
select sname
from student
where sno in (select sno from sc);
#(5) 查询所有学生的信息和所选修的课程, 要求显示学生的学号、姓名、课程号及课程名。 没有选课的同学对应的选课信息为空。
select DISTINCT student.sno,student.sname,sc.cno,cname
from student
left join sc on student.sno=sc.Sno
left JOIN courses c on sc.cno=c.cno
#(6) 查询所有课程的课程编号、课程名称及选课人数,没有被选的课程选课人数显示为0。
select courses.cno,cname,count(sc.cno) as 选课人数
from courses left join sc on courses.cno=sc.cno
group by courses.cno,cname;
#(7) 列出所有学生所有可能的选修情况,要求显示学生的学号、姓名、课程号及课程名。
select sno,sname,cno,cname
from student,courses
order by sno
#(8) 查找计算机系的学生选修课程数大于2 的学生的姓名、 平均成绩和选课门数,并按平均成绩降序排列。
select sname,avg(grade) as 平均成绩,count(cno) as 选课门数
from student,sc where student.sno=sc.sno and sdep ='计算机'
group by sname
having count(cno)>2
order by AVG(grade) desc