/*思路** 题目:如何解决取一个班成绩中前N名? 求前N名给我的第一个感觉 我想到了 sqlserver中 Top 函数 但是MySQL中并没有这个函数。 我们先按成绩排序,再找到 第N名在哪儿个位置,直接用limit N 便可以求出 那我们如果确认第N名的位置呢? 很简单,我们按成绩降序排序并分组(因为有并列情况) 生成中间表 记为 B表 此时 我们要求前 N 名 我们就取出 B表 前N条记录 然后求个数的和。 这个和 即为 第N名的最后一个(第N名可能存在并列情况) ****/**
create PRocedure findTop3(IN topN int)begindeclare limitLen int default 0; select sum(E.b) into limitLen from( select B.* from( select count(*) as b from score group by marks order by marks desc ) as B limit topN )as E ;select * from score order by marks desc limit limitLen;end/**********测试数据********************* score 表: mysql> select *from score; +—-+——-+ | id | marks | +—-+——-+ | 1 | 99 | | 2 | 99 | | 3 | 100 | | 4 | 99 | | 5 | 68 | | 6 | 89 | | 7 | 90 | +—-+——-+
score 表结构: +——-+———+——+—–+———+—————-+ | Field | Type | Null | Key | Default | Extra | +——-+———+——+—–+———+—————-+ | id | int(11) | NO | PRI | NULL | auto_increment | | marks | int(11) | YES | | NULL | | +——-+———+——+—–+———+—————-+
测试结果: (1)mysql> call findTop3(3); +—-+——-+ | id | marks | +—-+——-+ | 3 | 100 | | 1 | 99 | | 2 | 99 | | 4 | 99 | | 7 | 90 | +—-+——-+ (2)mysql> call findTop3(5); +—-+——-+ | id | marks | +—-+——-+ | 3 | 100 | | 1 | 99 | | 2 | 99 | | 4 | 99 | | 7 | 90 | | 6 | 89 | | 5 | 68 | +—-+——-+
**************************************************/
新闻热点
疑难解答