【问题标题】:SQL - How to retrieve 5 most recent comments for each userSQL - 如何为每个用户检索 5 个最近的评论
【发布时间】:2020-10-20 01:32:55
【问题描述】:

我有一个名为“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  |
| ...|         |                     |                      |         

我需要做的是为每个 user_id 选择 5 个最近的(字段“日期”)条目

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

【问题讨论】:

  • 哪个版本的mysql?
  • 是版本 5.*
  • 我尝试了很多东西,相信我...但没有任何意义

标签: mysql sql date select greatest-n-per-group


【解决方案1】:

在 MySQL 5.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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      相关资源
      最近更新 更多