获取每个帖子的最后三个用户的所有操作

时间:2013-02-17 20:08:31

标签: mysql sql database greatest-n-per-group

last Question中,我询问是否从历史记录表中确定最后三个用户的所有操作,该记录表存储用户在延期帖子上完成的所有操作,现在我想要的是获得相同的东西,但每个帖子

每个帖子的最后三位用户的所有操作

history table
     id     | post_id | action    |  user_id
     1      |  5      | 1         |  3
     1      |  23     | 2         |  1
     2      |  24     | 2         |  6
     3      |  34     | 1         |  7
     4      |  35     | 1         |  1
     5      |  36     | 1         |  1
     6      |  23     | 2         |  3
     7      |  24     | 2         |  1
     8      |  23     | 1         |  4
     9      |  24     | 1         |  5
     10     |  24     | 1         |  1
     11     |  23     | 1         |  2
     12     |  23     | 4         |  1

感谢和抱歉,如果它似乎是一个重复的帖子

2 个答案:

答案 0 :(得分:1)

我认为这会奏效:

SELECT  a.user_ID, a.post_id, a.action
FROM    tableName a
        INNER JOIN
        (
            SELECT  DISTINCT 
              @curRow:=IF(@prevRow=post_Id,@curRow+1,1) rn,
              user_ID, 
              Post_Id, 
              @prevRow:=Post_Id
            FROM    (
                SELECT DISTINCT Post_Id, User_Id
                FROM TableName
                ORDER   BY Post_Id, ID DESC 
              ) t  
              JOIN (SELECT @curRow:= 0) r

        ) b ON a.post_id = b.post_id AND a.user_id = b.user_id
WHERE b.rn <= 3
ORDER   BY a.post_id, a.User_ID

Fiddle

答案 1 :(得分:0)

这可能是你想要的吗?

代码:

SELECT  a.user_ID,
group_concat(a.post_id),
group_concat(a.action)
FROM    tableName a
        INNER JOIN
        (
            SELECT  DISTINCT user_ID
            FROM    tableName   
            ORDER   BY ID DESC
            LIMIT   3
        ) b ON a.user_ID = b.user_ID
group by a.user_id
ORDER   BY a.User_ID;


| USER_ID | GROUP_CONCAT(A.POST_ID) | GROUP_CONCAT(A.ACTION) |
--------------------------------------------------------------
|       2 |                       7 |                      3 |
|       3 |                   5,5,4 |                  1,2,5 |
|       6 |                       7 |                      2 |