簡體   English   中英

Mysql 查詢獲取基於日期的最后三個記錄,沒有限制

[英]Mysql Query to get last three records based on date without Limit

所以我有一個遺留系統,它有一個如下表,一本書可以有多個評論

書評

review_id book_id 日期
28163 2234 2021-01-12 07:58:14
28261 2212 2021-01-18 12:39:10
28153 2199 2021-01-12 08:03:53
28206 2194 2021-01-18 07:41:49
28250 2194 2021-01-18 07:33:23
28152 2194 2021-01-12 08:03:52
28118 2194 2021-01-11 07:14:34
28057 2194 2021-01-08 07:32:21
28061 2194 2021-01-08 07:30:54
28211 2193 2021-01-18 07:40:32

我必須為每本書提取 3 條最近的評論,如下所示

review_id book_id 日期
28163 2234 2021-01-12 07:58:14
28261 2212 2021-01-18 12:39:10
28153 2199 2021-01-12 08:03:53
28206 2194 2021-01-18 07:41:49
28250 2194 2021-01-18 07:33:23
28152 2194 2021-01-12 08:03:52
28211 2193 2021-01-18 07:40:32

我嘗試使用 LIMIT,但我的 MYSQL 版本是史前版本,不允許子查詢中的限制。 有沒有更好的加入方法可以達到同樣的效果。

在舊版本的 MySQL 中,我建議使用變量作為最有效的方法:

select t.*
from (select t.*,
             (@rn := if(@b = book_id, @rn + 1,
                        if(@b := book_id, 1, 1)
                       )
             ) as rn
      from (select t.* from t order by book_id, review_date desc
           ) t cross join
           (select @b := -1, @rn := 0) params
     ) t
where rn <= 3;

使用解析 function 如下:

select t.* from
(select t.*,
       row_number() over (partition by book_id order by review_Date desc) as rn
  from your_Table t) t
where rn <= 3

如果您的 Mysql 版本低於 8,那么您可以使用如下關聯查詢:

select t.* 
  from your_table t
 where 3 >= (select count(*) from your_table tt
               where t.book_id = tt.book_id and tt.review_date <= t.review_Date)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM