select * from table where stage_id = 44 order by total limit 5
union all
select * from table where stage_id = 45 order by total limit 5
union all
select * from table where stage_id = 46 order by total limit 5
union all
select * from table where stage_id = 47 order by total limit 5
union all
select * from table where stage_id = 48 order by total limit 5
union all
select * from table where stage_id = 49 order by total limit 5
union all
select * from table where stage_id = 50 order by total limit 5
union all
select * from table where stage_id = 51 order by total limit 5
解释一下:where中的select是保证遍历所有记录,取每条记录与当前记录做比较,只有当table表中同一stage_id且不超过5个人的total比当前选择item的total高时,这个item就算是每组total排行的前5名。
虽然看起来很奇怪,但是我感觉这种方式效率高,易理解,易读.
数据量很小的时候可以用子查询,数据量很大的时候最好是一条条的查
谢邀。对于
select top n by group的问题,楼上的也给出了一些解决思路,我就不贴sql了。推荐两个链接给你看看。how-to-select-the-firstleastmax-row-per-group-in-sql
get-top-n-records-for-each-group-of-grouped-results
数据库不擅长逻辑处理,这些还是由程序来处理较好,另外我也是小白,为何没看到group by 和order by