php - 求一条sql语句 (分组取前五名)
怪我咯
怪我咯 2017-04-10 18:01:09
[PHP讨论组]

mysql数据库字段如上图所示,我现在的需求是
就是按stage_id分组后,按照total由大到小递减取得前5条,
现在每一组有30条,总共有8组,
我不想用for循环,循环8次,每次取5条,大家有没有高效的sql语句,求解答

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(6)
ringa_lee
select * from table as a where (select count(distinct(total)) from table as b where a.stage_id = b.stage_id and b.total > a.total) < 5;

解释一下:where中的select是保证遍历所有记录,取每条记录与当前记录做比较,只有当table表中同一stage_id且不超过5个人的total比当前选择item的total高时,这个item就算是每组total排行的前5名。

高洛峰

虽然看起来很奇怪,但是我感觉这种方式效率高,易理解,易读.

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
PHP中文网
select t1.* from test t1
WHERE (select COUNT(*) from test t2 where t2.stage_id= t1.stage_id and t2.total > t1.total) < 5
ORDER BY t1.stage_id,t1.total 
天蓬老师

数据量很小的时候可以用子查询,数据量很大的时候最好是一条条的查

PHP中文网

谢邀。对于 select top n by group 的问题,楼上的也给出了一些解决思路,我就不贴sql了。推荐两个链接给你看看。

  1. how-to-select-the-firstleastmax-row-per-group-in-sql

  2. get-top-n-records-for-each-group-of-grouped-results

迷茫

数据库不擅长逻辑处理,这些还是由程序来处理较好,另外我也是小白,为何没看到group by 和order by

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号