通过内连接获取学生的总成绩排名前二的学生姓名
成绩表的字段:xueshenghao,yu,shu,yy均为int类型。学生表的字段:id(int),name(varchar)。学生表中的id就是成绩表中的学生号(这里可以使用一个外键,但此节暂不涉及外键知识)。需求:通过两个表获取总成绩排名前二的学生姓名以及总成绩。
成绩表 学生表
1.暂时不考虑总成绩相等的情况
select xueshengbiao.`name`, (chengjibiao.yu+chengjibiao.shu+chengjibiao.yy) zongchengji from chengjibiao inner JOIN xueshengbiao on xueshengbiao.id=chengjibiao.xueshenghao ORDER BY (chengjibiao.yu+chengjibiao.shu+chengjibiao.yy) desc LIMIT 2;
2.考虑总成绩相等的情况(排名规则:如果有两个一等奖成绩相同,则仅次于一等奖成绩的人为三等奖;如果一等奖一人,二等奖多人,则要查出所有的二等奖)
select xueshengbiao.`name`, (chengjibiao.yu+chengjibiao.shu+chengjibiao.yy) zongchengji from chengjibiao inner JOIN xueshengbiao on xueshengbiao.id=chengjibiao.xueshenghao and chengjibiao.yu+chengjibiao.shu+chengjibiao.yy>=(select (chengjibiao.yu+chengjibiao.shu+chengjibiao.yy) zongchengji from chengjibiao ORDER BY (chengjibiao.yu+chengjibiao.shu+chengjibiao.yy) desc LIMIT 1,1)ORDER BY zongchengji desc;