如何在一组数据中进行排序,并在MySQL查询中按每组内的最大值对组进行排序

时间:2010-08-14 06:53:09

标签: mysql

我有一个看起来像这样的数据集:

id  entry_id  the_data
1      100       Z
2      300       B
3      100       C
4      200       F
5      300       Q
6      300       A
7      300       L
8      100       N
9      200       O

结果应该只为每个相应的条目(通过entry_id)提供3个最近的记录(按id),它们需要组合在一起(通过entry_id),按降序排序(通过id)和(棘手的部分)分组集需要按最近记录(按子集中的最高ID)降序排序,下一个子集中次高,依此类推。

因此,期望的结果应如下所示:

id  entry_id  the_data
9      200       O
4      200       F
8      100       N
3      100       C
1      100       Z
7      300       L
6      300       A
5      300       Q

此查询已关闭,但无法按每个组中的最大ID对记录分组进行排序

select t1.id, t1.entry_id, t1.the_data
from mytable t1
where (
    select count(t2.id) from mytable t2
    where t2.entry_id = t1.entry_id and t2.id > t1.id
) <= 2
order by t1.entry_id desc, t1.id desc

结果如下:

id  entry_id  the_data
7      300       L
6      300       A
5      300       Q
9      200       O
4      200       F
8      100       N
3      100       C
1      100       Z

如何完成此查询以提供上述所需结果?

1 个答案:

答案 0 :(得分:0)

引入一个子查询,该子查询获取每个entry_id分组,加入和排序的最大ID,并且您已完成...

select t1.id, t1.entry_id, t1.the_data
from mytable t1
inner join (
    select entry_id, MAX(id) AS maxid
    from mytable
    group by entry_id
) maxs
on maxs.entry_id = t1.entry_id
where (
    select count(t2.id) from mytable t2
    where t2.entry_id = t1.entry_id and t2.id > t1.id
) <= 2
order by maxs.maxid desc, t1.entry_id desc, t1.id desc