简体   繁体   中英

Query of getting distinct latest value from table

In MySQL I am trying to get the only one latest data of each user. I am cureently doing the following query

SELECT DISTINCT username, value, date
FROM table
WHERE date >=  CURDATE()
ORDER BY date DESC

Its returning all the values by username and the query is to slow. Is there any way to make it faster and get only one latest value of each user?

mostly if you are looking for latest date of each username. Hope this query helps

SELECT  T.username, T.value, TT.date
FROM table T
WHERE T.Date = (SELECT MAX(TT.Date)
                 FROM table TT
                 WHERE TT.user = T.user)

Do a GROUP BY with MAX() in a sub-query to find each user's last date. Join with that result:

SELECT t1.username, t1.value, t1.date
FROM table t1
JOIN (select username, max(date) as maxdate from table
      group by username) t2 on t1.username = t2.username
                           and t1.date = t2.maxdate
WHERE t1.date >= CURDATE()
ORDER BY t1.date DESC

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