Selecting most recent as part of group by (or other solution …)

时间秒杀一切 提交于 2019-12-13 14:28:46

问题


I've got a table where the columns that matter look like this:

username
source
description

My goal is to get the 10 most recent records where a user/source combination is unique. From the following data:

1 katie    facebook    loved it!
2 katie    facebook    it could have been better.
3 tom      twitter     less then 140
4 katie    twitter     Wowzers!

The query should return records 2,3 and 4 (assume higher IDs are more recent - the actual table uses a timestamp column).

My current solution 'works' but requires 1 select to generate the 10 records, then 1 select to get the proper description per row (so 11 selects to generate 10 records) ... I have to imagine there's a better way to go. That solution is:

SELECT max(id) as MAX_ID, username, source, topic
FROM   events
GROUP BY source, username
ORDER BY MAX_ID desc;

It returns the proper ids, but the wrong descriptions so I can then select the proper descriptions by the record ID.


回答1:


Untested, but you should be able to handle this with a join:

SELECT
    fullEvent.id,
    fullEvent.username,
    fullEvent.source,
    fullEvent.topic
FROM
    events fullEvent JOIN
    (
        SELECT max(id) as MAX_ID, username, source
        FROM   events
        GROUP BY source, username
    ) maxEvent ON maxEvent.MAX_ID = fullEvent.id
ORDER BY fullEvent.id desc;


来源:https://stackoverflow.com/questions/8593908/selecting-most-recent-as-part-of-group-by-or-other-solution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!