0

最后一个问题中,我询问了如何从历史表中获取最后三个用户的所有操作,该表存储用户在延期帖子上所做的所有操作,现在我想要的是获得相同的东西,但对于每个帖子

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

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

谢谢,对不起,如果它似乎是重复的帖子

4

2 回答 2

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

还有小提琴

于 2013-02-17T20:24:43.463 回答
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 |
于 2013-02-17T20:24:03.037 回答