简体   繁体   English

使用 GROUP_CONCAT 时,如何获取每个组的最新 2 条记录?

[英]How can i get just the latest 2 records on each group when using GROUP_CONCAT?

SELECT id, GROUP_CONCAT(type SEPARATOR '/') as types FROM `sems` GROUP by year

I just want to get the 2 latest record on each group我只想获得每组的 2 条最新记录

If you are running MySQL 8.0, you can use row_number() for this.如果您正在运行 MySQL 8.0,则可以为此使用row_number() You need an ordering column to define the latest record, I assumed ordering_id :您需要一个排序列来定义最新记录,我假设ordering_id

select id, group_concat(type order by rn separator '/') types
from (
    select id, type, row_number() over(partition by id order by ordering_id desc) rn
    from sems
) t
where rn <= 2
group by id

In earlier versions, one option is to filter with a subquery:在早期版本中,一种选择是使用子查询进行过滤:

select id, group_concat(type order by rn separator '/') types
from sems s
where s.ordering_id >= (
    select s1.ordering_id
    from sems s1
    where s1.id = s.id
    order by s1.ordering_id desc
    limit 2
)
group by id

This assumes that (id, ordering_id) tuples are unique.这假设(id, ordering_id)元组是唯一的。 If not, and there are ties in the top 2, all related records will be taken into account.如果不是,并且前 2 名存在平局,则将考虑所有相关记录。

If your data is not too numerous, you can use:如果您的数据不是太多,您可以使用:

SELECT id,
       SUBSTRING_INDEX(GROUP_CONCAT(type ORDER BY ? DESC SEPARATOR '/'), '/', -2) as types
FROM `sems`
GROUP by year;.

The ? ? is for the column used to define "latest"用于定义“最新”的列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM