mysql分组取前N记录

http://blog.csdn.net/acmain_chm/article/details/4126306php

http://bbs.csdn.net/topics/390958705html

 

1mysql

我只用到了其中的特殊形式,就是 分组取最新的一条记录:sql

select *
from (select * from Table1 order by Score desc) t
group by ClsNo

利用的是 group by 只取第一条记录须要用子查询先把须要的记录排序到第一位app

2018/8/21 排序好像无用,不能倒叙 url

2 下面这几个都是利用子查询验证当前记录是否知足前n这个条件spa

select * 
from Table1 a
where not exists (select 1 from Table1 where ClsNo=a.ClsNo and Score>a.Score);

这个是利用子查询先查出小于最高值的记录,再排除出最高记录(感受绕了一圈).net

 

3 原理相似,利用子查询查找排序前n位的记录id并比较code

where id in( select id from tb1 where cataid = a.cataid order by score limit 0,10)

所用的msyql不支持:limit 在 in语句中不被支持server

 

4 原理相似,子查询查找小于当前排名的记录数,必须小于n才行

where 2 > ( select count(*) from tb1 where bid = a.bid and cid < a.cid )
相关文章
相关标签/搜索