2

我有一张包含用户帖子的表格。我需要每天从每个用户显示 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
4

1 回答 1

0

试试这个糟糕的 SQL 代码 :)

select post_id, user_id, post_datetime, post_text from (
  select posts.*,
    if (user_id = @prev_user and date(post_datetime) = date(@prev_day),
      @row := @row + 1, @row := 1) idx,
    @prev_user := user_id,
    @prev_day := post_datetime
  from posts, (select @row := 1, @prev_user := null, @prev_day := null) init
  order by date(post_datetime), user_id, post_datetime desc
) s
where s.idx <= 2

结果:

+---------+---------+---------------------------------+----------------+
| POST_ID | USER_ID |          POST_DATETIME          |   POST_TEXT    |
+---------+---------+---------------------------------+----------------+
|       4 |     100 | December, 01 2012 04:00:00+0000 | lorem ipsum 4  |
|       2 |     100 | December, 01 2012 02:00:00+0000 | lorem ipsum 2  |
|       3 |     101 | December, 01 2012 03:00:00+0000 | lorem ipsum 3  |
|       5 |     102 | December, 01 2012 05:00:00+0000 | lorem ipsum 5  |
|       6 |     100 | December, 02 2012 03:00:00+0000 | lorem ipsum 6  |
|      10 |     101 | December, 02 2012 07:00:00+0000 | lorem ipsum 10 |
|       9 |     101 | December, 02 2012 06:00:00+0000 | lorem ipsum 9  |
|       7 |     102 | December, 02 2012 04:00:00+0000 | lorem ipsum 7  |
+---------+---------+---------------------------------+----------------+

在这里拉小提琴。

我认为如果按日期降序排序会更合适,因为您实际上得到的是最接近当前日期的前 2 个。

于 2012-12-11T02:15:56.883 回答