我有一张包含用户帖子的表格。我需要每天从每个用户显示 1 到最多 n 个帖子。
例子:
post_id|user_id|post_datetime|post_text
1 |100 |2012-12-01 01:00:00|lorem ipsum 1
2 |100 |2012-12-01 02:00:00|lorem ipsum 2
3 |101 |2012-12-01 03:00:00|lorem ipsum 3
4 |100 |2012-12-01 04:00:00|lorem ipsum 4
5 |102 |2012-12-01 05:00:00|lorem ipsum 5
6 |100 |2012-12-02 03:00:00|lorem ipsum 6
7 |102 |2012-12-02 04:00:00|lorem ipsum 7
8 |101 |2012-12-02 05:00:00|lorem ipsum 8
9 |101 |2012-12-02 06:00:00|lorem ipsum 9
10 |101 |2012-12-02 07:00:00|lorem ipsum 10
我需要一个查询,例如,每个用户每天最多返回 2 个帖子:
post_id|user_id|post_datetime|post_text
2 |100 |2012-12-01 02:00:00|lorem ipsum 2
4 |100 |2012-12-01 04:00:00|lorem ipsum 4
3 |101 |2012-12-01 03:00:00|lorem ipsum 3
5 |102 |2012-12-01 05:00:00|lorem ipsum 5
6 |100 |2012-12-02 03:00:00|lorem ipsum 6
7 |102 |2012-12-02 04:00:00|lorem ipsum 7
9 |101 |2012-12-02 06:00:00|lorem ipsum 9
10 |101 |2012-12-02 07:00:00|lorem ipsum 10
我尝试使用 GROUP 和 HAVING 但我只获得前 n 条记录,而不是每个用户每天的前 n 条记录:
SELECT a.* FROM posts AS a
JOIN posts AS a2
ON a.user_id = a2.user_id AND a.post_datetime <= a2.post_datetime
GROUP BY a.post_id
HAVING COUNT(*) <= 3
ORDER BY a.post_id, a.post_datetime DESC