当前位置:网站首页>如何优雅的获取每个分组的前几条数据
如何优雅的获取每个分组的前几条数据
2022-07-05 04:06:00 【沛沛老爹】
背景
最近在改一个功能时,发现有个需要获取每个问题回答的前3条的最优回复内容。
然后组合成list。返回给到前端。
大家可能觉得这个比较简单,找出所有的来,然后一个for循环,解决完事。
但是作为有理想的,装逼的程序员,我们怎么能做这样的操作?
解决方案
一、使用mysql解决
这个方案网上比较常见。
SQL贴上
select media_id from article a
where 3>=(select count(1) from article where `status`=1 and media_id=a.media_id and hot_num > a.hot_num)
order by a.media_id,id desc;
二、使用stream的groupBy解决
Map<String, List<Article>> map = list.stream()
.collect(Collectors.groupingBy(Article::getMediaId,
Collectors.collectingAndThen(Collectors.toList(),
list2 -> list2.stream().sorted(Comparator.comparing(Article::getHdNum, Comparator.reverseOrder())).limit(3).collect(Collectors.toList()))));
总结
第二种方式中查询的数据有点大,建议还是用第一种好点。
边栏推荐
猜你喜欢
As soon as I write the code, President Wang talks with me about the pattern all day
UI自动化测试从此告别手动下载浏览器驱动
【UNIAPP】系统热更新实现思路
Why do big companies such as Baidu and Alibaba prefer to spend 25K to recruit fresh students rather than raise wages by 5K to retain old employees?
Use Firefox browser to quickly pick up Web image materials
Is "golden nine and silver ten" the best time to find a job? Not necessarily
“金九银十”是找工作的最佳时期吗?那倒未必
mysql的七种join连接查询
[understand series after reading] 6000 words teach you to realize interface automation from 0 to 1
Uni app common functions /api
随机推荐
[wp]bmzclub writeup of several questions
【刷题】BFS题目精选
[数组]566. 重塑矩阵-简单
MacBook安装postgreSQL+postgis
Use threejs to create geometry and add materials, lights, shadows, animations, and axes
Resolved (sqlalchemy+pandas.read_sql) attributeerror: 'engine' object has no attribute 'execution_ options‘
The order of LDS links
Longyuan war "epidemic" 2021 network security competition web easyjaba
A real day for Beijing programmers!!!!!
provide/inject
Interview byte, pass the exam and directly work on three sides. As a result, I found an architect to hang me?
Seven join join queries of MySQL
基于TCP的移动端IM即时通讯开发仍然需要心跳保活
Common features of ES6
Rust区块琏开发——签名加密与私钥公钥
A application wakes up B should be a fast method
[wp][introduction] brush weak type questions
Containerd series - detailed explanation of plugins
ActiveReportsJS 3.1 VS ActiveReportsJS 3.0
NEW:Devart dotConnect ADO.NET