如何获取MySQL中的最新值?
How to get the latest value in MySQL?
如何获取每个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.2 或更高版本中,您可以使用 CTE
和 window 函数:
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
如何获取每个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.2 或更高版本中,您可以使用 CTE
和 window 函数:
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