获取每个组的最新n条记录

编程入门 行业动态 更新时间:2024-10-10 05:22:43
本文介绍了获取每个组的最新n条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

让我们说一下下表:

id coulmn_id value date 1 10 'a' 2016-04-01 1 11 'b' 2015-10-02 1 12 'a' 2016-07-03 1 13 'a' 2015-11-11 2 11 'c' 2016-01-10 2 23 'd' 2016-01-11 3 11 'c' 2016-01-09 3 111 'd' 2016-01-11 3 222 'c' 2016-01-10 3 333 'd' 2016-01-11

对于n = 3,我想获取每个ID的最新n条记录<== 3.所以我将得到以下输出:

for n = 3, I want to get the latest n records<=3 for each id. So I will have the following output:

id column_id value date 1 10 'a' 2016-04-01 1 12 'a' 2016-07-03 1 13 'a' 2015-11-11 2 11 'c' 2016-01-10 2 23 'd' 2016-01-11 3 111 'd' 2016-01-11 3 222 'c' 2016-01-10 3 333 'd' 2016-01-11

推荐答案

我正在回答,因为所引用的问题的答案不稳定(我将在此处对此发表评论).

I am answering because the referenced question has an unstable answer (I'll comment on that there).

这是一种可行的解决方案:

Here is a solution that should work:

select t.* from (select t.*, (@rn := if(@id = id, @rn + 1, if(@id := id, 1, 1) ) ) as seqnum from t cross join (select @rn := 0, @id := -1) params order by id, date desc ) t where seqnum <= 3;

解决方案的区别在于,变量赋值都在单个表达式中. MySQL不保证对表达式求值的顺序,因此,如果代码能够始终如一地工作,这非常重要.

The difference in the solutions is that the variable assignments are all in a single expression. MySQL does not guarantee the order of evaluation of expressions, so this is very important if the code is going to work consistently.

更多推荐

获取每个组的最新n条记录

本文发布于:2023-10-26 17:57:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530912.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最新

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!