本文通过最经典的“学生-成绩-课程-教师”表来帮助练习sql语句。
STUDENT表
- SNO 学号
- SNAME 姓名
- SSEX 性别
- SBIRTHDAY 生日
- CLASS 班级
SCORE表
- SNO 学号
- CNO 课程编号
- DEGREE 分数
COURSE表
- CNO 课程编号
- CNAME 课程名称
- TNO 教师编号
TEACHER表
- TNO 教师编号
- TNAME 教师姓名
- TSEX 性别
- TBIRTHDAY 生日
- PROF 职称
- DEPART 系部
1. 查询“12”班学生所选各个课程的平均分。
select CNO, avg(DEGREE)
from SCORE
where SNO in (select SNO
from STUDENT
where CLASS = '12')
group by CNO
2. 查询和学号为108的同学同年出生的所有学生的Sno、Sname和Sbirthday列。
select
SNO,
SNAME,
SBIRTHDAY
from STUDENT
where year(SBIRTHDAY) = (
select year(SBIRTHDAY)
from STUDENT
where SNO = '108'
);
3. 查询“李明“教师任课的学生成绩。
select *
from SCORE
where CNO in (
select CNO
from COURSE
inner join TEACHER on COURSE.TNO = TEACHER.TNO and TNAME = '李明'
);
4. 查询选修某课程的同学人数多于5人的教师姓名。
select TNAME
from TEACHER
where TNO in (
select TNO
from COURSE
where CNO in (select CNO
from SCORE
group by CNO
having count(SNO) > 5)
);
5. 查询“计算机系”中与“电子工程系“不同职称的教师的Tname和Prof。
select
tname,
prof
from TEACHER
where depart = '计算机系' and prof not in (
select prof
from TEACHER
where depart = '电子工程系'
);
6. 查询所有教师和同学的name、sex和birthday。
select
TNAME name,
TSEX sex,
TBIRTHDAY birthday
from TEACHER
union
select
sname name,
SSEX sex,
SBIRTHDAY birthday
from STUDENT;
7. 查询成绩比该课程平均成绩低的同学的成绩表。
select *
from score
join (select CNO, avg(DEGREE) as avg from SCORE group by CNO) t1
on score.sno = t1.cno
where score.degree < t1.avg;
8. 查询所有未讲课教师的Tname和Depart。
select TNAME,DEPART
from teacher
where TNO not in (select distinct(TNO) from course);
9. 查询至少有2名男生的班号。
select class
from student
where SSEX = '男'
group by class
having count(SSEX)>1
10. 查询Student表中每个学生的姓名和年龄。
select
SNAME,
year(now()) - year(SBIRTHDAY)
from STUDENT;
11. 查询和“李军”同性别并同班的同学Sname。
select sname
from STUDENT
where (SSEX, CLASS) = (select
SSEX,
CLASS
from STUDENT
where SNAME = '李军');