在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
感谢并抱歉,如果它看起来是重复的帖子
最佳答案
我认为这会起作用:
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 .
关于mysql - 获取每个帖子的最后三个用户的所有操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14925524/