表结构如下:
- 学生资料表
- 学生的成绩表,sid就是学生资料表的外键
分数最高的学生信息,科目
方法一:左连接
select s.course as 科目,max(s.score1) as 最高分,c.name as 姓名 from score s left join student c on c.id = s.sid group by s.course;
方法二:子查询
select course as 科目,max(score1) as 最高分,(select name from student c where c.id=s.sid) as 姓名 from score s group by course;
科目评价为良好,性别为女的学生信息,科目
select s.score1,s.course,c.name,c.sex from score s join student c on s.sid=c.id where s.comment='良好' and c.sex='女';
最低分数性别为男和女的信息
select course,min(score1) as 最低分,c.sex,c.name from score s join student c on s.id=c.id and c.sex='男' or sex='女' group by course;
每科的前两名学生信息
select course,score1, c.name from score s1 left join student c on c.id=s1.sid where 2>(select count(*) from score s where s.course = s1.course and s.score1>s1.score1) order by s1.course,s1.score1
还有其他的两种方法可以取前两名学生数据:
方法二:select a.id,a.SName,a.ClsNo,a.Scorefrom Table1 a left join Table1 b on a.ClsNo=b.ClsNo and a.Score<b.Scoregroup by a.id,a.SName,a.ClsNo,a.Scorehaving count(b.id)<2order by a.ClsNo,a.Score desc
方法三:select *from Table1 awhere id in (select id from Table1 where ClsNo=a.ClsNo order by Score desc limit 2)order by a.ClsNo,a.Score desc