1 1到5
-- 1 查询课程编号为‘01’的课程比‘02’的课程成绩高的所有学生的学号(重点) -- 整体的机构是先把三个表合并起来,再用where语句进行筛选,这里的as都可以省略, -- select -- a.s_id as "sno", -- a.s_score as "01", -- b.s_score as "02", -- c.s_name -- from -- (select s_id,c_id,s_score from score where c_id = '01') as a -- inner join -- (select s_id,c_id,s_score from score where c_id = '02')as b -- on a.s_id = b.s_id -- inner join -- student as c on c.s_id = a.s_id -- where a.s_score > b.s_score -- 2 查询平均成绩大于60分的学生学号和平均成绩 -- -- 注意select后面的列尽量只选在group by后面出现的字段或使用统计函数统计过的字段,不要添加其它的列,因为没有意义 -- select s_id, avg(s_score), c_id -- from score -- group by s_id having avg(s_score)>60 -- 3 查询所有同学的学号、姓名、选课总数、总成绩 -- 使用的表:student,score -- 由于有的学生可能没有成绩,所以这里用左连接, -- select后面尽量只出现groupby后面的字段和统计字段,所以把名字列也加到groupby后面 -- 为了避免求和列出现null值,所以判断为空值时赋值为0 -- select a.s_id,a.s_name, count(b.s_id), -- sum(case when b.s_score is null then 0 else b.s_score end) -- from student as a left join score as b on a.s_id = b.s_id -- group by s_id,a.s_name -- 4 查询姓猴老师的个数 -- 使用的表:teacher -- %代表任意字符,如果姓氏有重复可以用count(distinct t_name)来去重后再统计 -- select count(t_name) -- from teacher -- where t_name like '猴%' -- 5 查询没学过张三老师课的学生的学号,姓名(重点) -- 注意这里必须是用not in方法来解决,否则是错误的,即先把选过张三老师课程的学号找到,再取反 -- select s_id, s_name from student -- where s_id not in ( -- select s_id from score -- where c_id = ( -- select c_id from course -- where t_id = -- (select t_id from teacher where t_name = '张三') -- ) -- ) -- 错误写法,这样选出的是其它老师上的课 -- select * from score where c_id != '02' -- 先把三个表合并,再进行选择 -- select s_id, s_name from student -- where s_id not in -- ( -- select s.s_id from score as s -- inner join course as c on s.c_id = c.c_id -- inner join teacher as t on c.t_id = t.t_id -- where t.t_name = '张三' -- )