SQL - 如何为每个用户检索 5 个最近的评论

SQL - How to retrieve 5 most recent comments for each user

我有一个 table 叫做'user_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  |
| ...|         |                     |                      |         

我需要做的是 select 每个 user_id

的 5 个最新(字段 'date')条目

我搜索了很多,似乎我需要一个子查询,但我找不到正确的组合。

您可以使用 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;

在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