简体   繁体   中英

How to get the latest value in MySQL?

How to get the latest value in every artistID? I want to get the ww and 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 

In MariaDB 10.2 or later you can use a CTE and window functions:

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM