聚集函数
【SY2-27】查询学生2012314101选修课程的总学分数。
use fsyxscj
select sum ( distinct Ccredit )
from SC,Course
where SC.Cno=Course.Cno
and SC.Sno=2012314101;
5 查询结果分组
【SY2-28】 求各个课程号(Cno)及相应的选课人数。
use fsyxscj
select Cno,count(Cno)
from SC
group by Cno
【SY2-29】查询选修了2门或2门以上课程的学生学号(Sno)。
use fsyxscj
select Sno
from SC
group by Sno
HAVING COUNT(Cno)>=2
一、连接查询
1 等值连接查询
【SY3-01】等值连接 查询每个学生及其选修课程的情况。
use fsyxscj
select Student.*,Course.*
from Student,Course,SC
where Student.Sno=SC.Sno
and Course.Cno=SC.Cno
【SY3-02】自然连接 查询每个学生及其选修课程的情况。
use fsyxscj
select Course.Cno,Course.Cname,Course.Ccredit,Course.Cpno,Student.Sage,Student.Dno,Student.Sbirth,Student.Sname,Student.Sno,Student.Ssex
from Student,Course,SC
where Student.Sno=SC.Sno
and Course.Cno=SC.Cno
2 自身连接
【SY3-03】查询每一门课的间接先修课(即先修课的先修课)。
select A.Cno,A.Cname,B.Cpno
from Course A,Course B
where A.Cpno=B.Cpno
3 外连接
【SY3-04】SY3-02中的等值连接改为左连接。
use fsyxscj
select Student.Sage,Student.Dno,Student.Sbirth,Student.Sname,Student.Sno,Student.Ssex,SC.Cno,SC.Grade
from Student left outer join SC on(Student.Sno=SC.Sno)
以上左连接操作也可以用如下的右连接操作代替,其结果是否一样?
use fsyxscj
select Student.Sage,Student.Dno,Student.Sbirth,Student.Sname,Student.Sno,Student.Ssex,SC.Cno,SC.Grade
from Student right outer join SC on(Student.Sno=SC.Sno)
4 复合条件连接
【SY3-05】 查询每个学生的学号(Sno)、姓名(Sname)、选修的课程名(Cname)及成绩(Grade)。
本查询涉及到三个表的连接操作,完成该查询的SQL语句如下:
use fsyxscj
select Student.Sname,Student.Sno,Course.Cname,SC.Grade
from Student ,SC ,Course
where Student.Sno=SC.Sno
AND SC.Cno=Course.Cno
二、连接查询练习题
1.查询全体学生学号、姓名、性别、年龄和所在系;
use fsyxscj
select Student.Sname,Student.Sno,Student.Ssex,Department.Dname
from Student ,Department
where Student.Dno=Department.Dno
2.查询计算机系年龄在19岁以上的学生的学号、姓名、出生日期;
use fsyxscj
select Student.Sname,Student.Sno,Student.Sbirth
from Student ,Department
where Student.Sage>19
and Department.Dname='计算机系'
and Department.Dno=Student.Dno
3.查询选修了“数学”或“数据库”课程学生的学号、姓名、成绩;
select SC.Sno,Sname,Grade
from Student,Course,SC
where Student.Sno=SC.Sno
and Course.Cno=SC.Cno
and (Course.Cname='数据库'or Course.Cname='数学')