I have a table with non-unique value and date on it
How to select values by the given tuple with the latest datetime?
given tuple (foo, bar)
result should be
[(1, foo, 2024-05-29 03:38:12), (6, bar, 2024-05-29 08:36:14)]
id value date 1 foo 2024-05-29 03:38:12* 2 foo 2024-05-27 12:37:06 3 xxx 2024-05-29 08:17:24 4 foo 2024-05-27 13:45:03 5 bar 2024-05-28 12:56:04 6 bar 2024-05-29 08:36:14*
I tried with the MAX(date) and GROUP BY, but seems my mysql level not that good to get a result((
Thank you
2
Answers
On MySQL 8+ the
ROW_NUMBER()
window function provides one way to do this:Here is a version which would work on earlier versions of MySQL (5.7 and lower):
SELECT value, MAX(date) AS max_date FROM your_table GROUP BY value: This subquery calculates the latest date for each value across the entire table.
SELECT t.id, t.value, t.date FROM your_table t: This is selecting the columns you are interested in from your table.
INNER JOIN (…subquery…) AS latest ON t.value = latest.value AND t.date = latest.max_date: This join ensures that you only get the rows that match the latest date for each value as found in the subquery.