(1)select…from…where 基本子句的使用
① 在student表中查询出生日日期在2003年以前的学生的学号、姓名、电话和年龄;
select studentno as '学号',sname as '姓名',phone as '手机号',year(now())-year(birthdate) as '年龄' from student where year(birthdate)<2003;
② 在score表中查询期平时成绩高于90分的学生学号、课程号,并按照学号排序;
select distinct studentno as '学号',courseno as '课程号' from score where daily>90 order by studentno;
③ 查询学号分别为’18122221324’,‘18137221508’,’18137221509’学生的课程号、平时成绩和期末成绩;
select studentno as '学号',courseno as '课程号',daily as '平时成绩',final as '期末成绩' from score where studentno in('18122221324','18137221508','18137221509');
④ 查询选修课程号为c8123的学生的学号和期末成绩,并且要求平时成绩在85~100分之间;
select studentno as '学号',final as '期末成绩' from score where courseno = 'c08123' and daily between 80 and 95;
⑤ 在student表中显示所有赵姓学生的姓名、生日和Email;
select sname as '姓名',birthdate as '生日',Email as '邮箱' from student where sname like '赵%';
⑥ 在score表中显示平时成绩高于85分、期末成绩高于90分的学生学号、课程号和成绩;
select studentno as '学号',courseno as '课程号',daily as '平时成绩',final as '期末成绩' from score where daily>=85 and final>=90;
⑦ 查询计算机学院专业为“软件工程”或“网络技术”的教师的教师编号,姓名和职称;
select teacherno as '教师编号',tname as '姓名',prof as '职称' from teacher where department = '计算机学院' and (major = '软件工程' or major = '网络技术');
(2)排序、分组和限定记录的查询
① 在student表中输出高于800分的学生的学号,姓名,电话和入学成绩,并按照入学成绩的降序进行排序;
select studentno as '学号',sname as '姓名',entrance as '入学成绩' from student where entrance>850 order by entrance desc;
② 在score表中查询总评成绩大于85分的学生的学号,课程号,电话和总评成绩,并按照课程号的升序、再按总评成绩的降序进行排列。总评成绩计算方法如下:总评成绩=daily0.2+final0.8;
select courseno as '课程号',daily*0.2 + final*0.8 as '总评',studentno as '学号' from score where daily*0.2 + final*0.8 > 85 order by courseno,daily*0.2 + final*0.8 desc;
③ 利用group by 子句对score表数据分组,显示每个学生的学号和平均总评成绩,总评成绩计算方法如下:总评成绩=daily0.3+final0.7;
select studentno as '学号',round(avg(daily*0.3 + final*0.7),2) as '平均分' from score group by studentno;
④ 使用group by 关键字和group_concat()函数对score表的courseno字段进行分组查询。可以查看该学生选修的课程号;
select courseno as '课程号',group_concat(studentno) as '选课学生号' from score group by courseno;
⑤ 查询选课在2门以上且各门课程期末成绩均高于85分的学生的学号及其总成绩,查询结果按总成绩的降序进行排序;
select studentno as '学号',sum(daily*0.3 + final*0.7) as '总分' from score where final>=85 group by studentno having count(*)>=2 order by sum(daily*0.3 + final*0.7) desc;
⑥ 查询score表中期末成绩final高于90分的成绩,按照平时成绩daily进行升序排序,从编号1开始,查询3条记录;
select * from score where final>90 order by daily asc limit 1,3;
(3)聚合函数的使用
① 查询score表中期末总成绩大于275分的学生的学号,总成绩以及平均成绩;
select studentno as '学号',sum(final) as '总分',avg(final) as '平均分' from score group by studentno having sum(final)>275 order by studentno;
② 查询选修课程号为c05103的学生期末最高分,最低分以及之间相差的分数;
select max(final) as '最高分',min(final) as '最低分',max(final) - min(final) as '分差' from score where(courseno = 'c05103');
③ 查询score表中每个学生的期末成绩平均分和所有成绩的平均值;
select studentno as '学号',avg(final) as '期末成绩平均分' from score group by studentno with rollup;
最后一行即为所有成绩平均值