Q1:求出每科成绩前三的SQL语句?
问题定义与背景
求出每科成绩前三?
数据表的格式
create table `std_score`(
`sid` int comment '学生id',
`cid` int comment '课程id',
`score` int comment '成绩',
primary key(`sid`, `cid`)
)engine=INNODB;
答案与解析
答案
select * from std_score a
where (select count(*) from std_score b where a.cid=b.cid and b.cid>a.cid) < 3
order by cid,score desc;
解析:嵌套查询,每扫描 a 一条记录都会对比扫描 b 的全部记录。select count(*) from std_score b where a.cid=b.cid and b.cid>a.cid 则是找出比当前扫到 a 的记录的成绩更高的成绩的记录数,where(**)<3 则表示该记录数不能大于3(因为要找出前三的成绩)。
结果展示
结果展示
Q2:删除重复记录并保留一条