【问题标题】:How to get the latest value in MySQL?如何获取 MySQL 中的最新值?
【发布时间】:2020-08-20 20:46:05
【问题描述】:

如何获取每个artistID的最新值? 我想得到 ww 和 ee (id=2,3)

    id  title   genreID  countryID  artistID  albumID  reg_count  down_count  createdAt           
------  ------  -------  ---------  --------  -------  ---------  ----------  ------------------- 
     1  qq            1          4         1        1         87          48  2020-05-05 01:00:00 
     2  ww            1          4         1        2         56          52  2020-05-05 03:00:00 
     3  ee            1          4         8       15         34          26  2020-05-05 21:00:00 
     4  rr            1          4         8       16         83          51  2020-05-05 05:00:00 

【问题讨论】:

  • 哪个版本的 MariaDB?
  • 10.4.11-MariaDB
  • 查看 grouwise-max 标签。

标签: mysql mariadb groupwise-maximum


【解决方案1】:

在 MariaDB 10.2 或更高版本中,您可以使用 CTE 和窗口函数:

WITH CTE AS (
  SELECT *,
         ROW_NUMBER() OVER (PARTITION BY artistId ORDER BY createdAt DESC) AS rn
  FROM contentnew 
  WHERE genreID = 1 AND mainContent = 1 AND countryID = 4
)
SELECT id, title, genreID, countryID, artistID, albumID, reg_count, down_count, createdAt
FROM CTE
WHERE rn = 1

输出:

id  title   genreID     countryID   artistID    albumID     reg_count   down_count  createdAt
2   ww      1           4           1           2           56          52          2020-05-05 03:00:00
3   ee      1           4           8           15          34          26          2020-05-05 21:00:00

Demo on dbfiddle

【讨论】:

  • 谢谢尼克。那么我是MySQL的初学者。那么你能告诉我另一种在旧版本中使用它的方法吗?例如SELECT * FROM contentnew WHERE genreID = 1 AND mainContent = 1 AND countryID = 4;
  • @SatelBill 您的版本比 10.2 新,因此您应该能够毫无问题地使用此查询。如果您想添加 WHERE 子句,请参阅我的编辑(尽管我注意到您的示例数据中没有 mainContent 列)
猜你喜欢
  • 2020-11-10
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-06
  • 2010-11-26
  • 2016-07-05
相关资源
最近更新 更多