本节内容接着前两篇内容:
目录
3.41单表查询
5.group by 子句
【例3.48】查询平均成绩大于等于80分的学生学号和平均成绩。
错误示例:
因为where子句中是不能用聚集函数作为条件表达式的。
select Sno,avg(Grade)
from SC
where avg(Grade)>90
group by Sno;
正确答案:
select Sno,avg(Grade)
from SC
group by Sno
having avg(Grade)>=80;
若是删去having语句,查询结果为每一个学生的平均成绩,包括没有成绩的学生。
3.42连接查询
1.等值与非等值的连接查询
【例3.49】查询每个学生及其选修课程的情况。
select Student.*,SC.*
from Student,SC
where Student.Sno=SC.Sno;
查询出来的元组的个数,依据于SC中的元组个数。
删去where语句之后,结果变成下面这样,这就是笛卡尔乘积的结果,元组个数为两个表中元组个数的乘积,但是这个结果在一般情况下没有什么实际意义
select Student.*,SC.*
from Student,SC
【例3.50】对例3.49用自然连接完成。
select Student.Sno,Sname,Ssex,Sage,Sdept,Cno,Grade
from Student,SC
where Student.Sno=SC.Sno;
查询到的结果其实都是一样的,这是这里限制了显示出来的列。
还有就是,如果两个表中的列的属性名是一样的话,需要添加前缀加以区分。
【例3.51】查询选修2号课程且成绩在85分以上的所有学生的学号和姓名。
select Student.Sno,Sname
from Student,SC
where Student.Sno=SC.Sno and Cno='2' and Grade>85;
and前后的三者顺序在逻辑上可以任意改变,但是上面这个写法是一种比较高效的执行过程,计算较快。
2.自身连接
【例3.52】查询每一门课的间接先修课(即先修课的先修课)。
这个时候,需要使用Course表,还需要同时使用2次,这时可以取别名。
select first.Cno,second.Cpno
from Course first,Course second
where first.Cpno=second.Cno;
3.外连接
【例3.53】select Student.Sno,Sname,Ssex,Sage,Sdept,Cno,Grade
from Student left outer join SC on (Student.Sno=SC.Sno);
select Student.Sno,Sname,Ssex,Sage,Sdept,Cno,Grade
from Student left outer join SC on (Student.Sno=SC.Sno);
外连接依然可以保存悬浮数组,即使数据均为空值依然可以查询出来。
外连接还包括左连接和右连接。
但是使用where查询,就是自动的删去空值结果。
select Student.Sno,Sname,Ssex,Sage,Sdept,Cno,Grade
from Student ,SC
where Student.Sno=SC.Sno;
4.多表连接
【例3.54】查询每个学生的学号、姓名、选修的课程名及成绩。
select Student.Sno,Sname,Cname,Grade
from Student,Course,SC
where Student.Sno=SC.Sno and SC.Cno=Course.Cno;
若是不限制显示的结果,就会出现下面的超级大表。
所以必要时还是要有选择的查看自己需要的信息。
select Student.*,Course.*,SC.*
from Student,Course,SC
where Student.Sno=SC.Sno and SC.Cno=Course.Cno;
心得
这一节课的内容比较少,然后再每一个例题上都进行了一些简单的改变,看看他们都有什么不同,进行的很快,大部分课堂上老师都给演示了。