sql-如何为每个用户检索5条最新评论

pes8fvy9  于 2021-08-01  发布在  Java
关注(0)|答案(2)|浏览(319)

我有一个名为“user\u text”的表

| id | user_id |        date         |         text         |
|----|---------|---------------------|----------------------|
| 1  |    4    | 07/01/2019 10:04:11 | This is a test       |
| 2  |    9    | 19/11/2018 09:43:00 | Here's another test  |
| ...|         |                     |                      |

我需要做的是为每个用户id选择5个最近的(字段“date”)条目
我已经搜索了很多关于它,似乎不知何故我需要一个子查询,但我找不到正确的组合。

bpzcxfmw

bpzcxfmw1#

在MySQL5.x中,有一个选项使用相关子查询:

select u.*
from user_text u
where (
    select count(*)
    from user_text u1
    where u1.user_id = u.user_id and u1.date >= u.date
) <= 5
yyhrrdl8

yyhrrdl82#

你可以用 row_number() :

select t.*
from (select t.*, row_number() over (partition by user_id order by date desc) as seqnum
      from t
     ) t
where seqnum <= 5;

相关问题