student
course
teacher
score
1 查詢Score表中至少有5名學生選修的並以3開頭的課程的平均分數
select cno,avg(degree) from score group by cno having count(*)>=5 and cno regexp "^3"
思路:按課程分組,計算各課程選修人數,用正則表達式找到以3開頭的課程(此處也可以用like+通配符%)
2 查詢分數大於70,小於90的Sno列
select sno from score where degree between 70 and 90
3 查詢所有學生的Sname、Cno和Degree列
select sname,cno,degree from student st,score sc where st.sno = sc.sno order by sname
4 查詢所有學生的Sname、Cname和Degree列
select sname,cname,degree from score sc,student st,course c where sc.sno = st.sno and sc.cno = c.cno
5 查詢“95033”班學生各課程的平均分
select cname,format(avg(degree),2) avg_degree from score inner join course on score.cno = course.cno inner join (select sno from student where class = 95033)as c on c.sno=score.sno group by cname
6 查詢選修“3-105”課程的成績高於“109”號同學成績的所有同學的記錄
select sno,degree from score where cno = '3-105' and degree > (select degree from score where sno = 109 and cno = '3-105')
7 查詢和學號為108、101的同學同年出生的所有學生的Sno、Sname和Sbirthday列
select sno,sname,sbirthday from student where year(sbirthday) in (select year(sbirthday) from student where sno in(108,101))
8 查詢“張旭“教師任課的學生成績
#方法一 子句嵌套
select sno,cno,degree from score where cno = (select cno from course where tno = (select tno from teacher where tname = "張旭")) #方法二 多表聯結
select s.sno,s.cno,s.degree from score s,course c,teacher t where t.tname = "張旭" and t.tno = c.tno and c.cno = s.cno
9 查詢選修某課程的同學人數多於5人的教師姓名
#方法一
select tname from teacher where tno=(select tno from course where cno =(select cno from score group by cno having count(*)>5)) #方法二
select tname from teacher t,course c where t.tno = c.tno and c.cno = (select cno from score group by cno having count(*)>5)
10 查詢“計算 機系”與“電子工程系“不同職稱的教師的Tname和Prof
select Tname,Prof from Teacher where Depart ='計算機系' and Prof not in( select Prof from Teacher where Depart ='電子工程系') union select Tname,Prof from Teacher where Depart ='電子工程系' and Prof not in( select Prof from Teacher where Depart ='計算機系');
11 查詢選修編號為“3-105“課程且成績至少高於選修編號為“3-245”的同學的Cno、Sno和Degree,並按Degree從高到低次序排序
select Cno,Sno,Degree from Score where Cno = '3-105' and Degree > any(select Degree from Score where Cno = '3-245') order by Degree desc;
any some 表示集合內or關系 all是and關系
12 查詢成績比該課程平均成績低的同學的成績表
select * from score a where degree < (select avg(degree) from score b where b.cno=a.cno);
數據庫引擎逐條從主查詢取記錄與子查詢對比過濾
13 查詢至少有2名男生的班號
select class from student group by class having count(ssex="男")>=2