Skip to content
Advertisement

Select most recent row from MySQL for set of distinct keys

I have a table foo that looks like this:

+----------+--------------+------+-----+-------------------+----------------+
| Field    | Type         | Null | Key | Default           | Extra          |
+----------+--------------+------+-----+-------------------+----------------+
| id       | int(10)      | NO   | PRI | NULL              | auto_increment |
| ts       | timestamp    | NO   |     | CURRENT_TIMESTAMP |                |
| user     | varchar(255) | YES  | MUL | NULL              |                |
| a        | varchar(255) | YES  | MUL | NULL              |                |
| b        | varchar(255) | YES  | MUL | NULL              |                |
| c        | float        | YES  |     | NULL              |                |
+----------+--------------+------+-----+-------------------+----------------+

For each set of distinct (user, a, b), I’d like to select the most recent timestamp and the value c

I’ve tried a few variations of the following without any luck

select distinct user, b, c, ts as ts_b 
from (select max(ts) as ts_a from foo as max_ts) 
where ts_a = ts_b;

Advertisement

Answer

How about

select user,b,c, max(ts) as ts_b from foo
group by user,b,c

UPDATE

you can use this subquery to get what you need. f2 will be the foo row that matches the distinct user,a,b and has the latest ts. This is equivalent to the CROSS APPLY statement in MSSQL.

select f2.user,f2.a, f2.b,f2.c, f2.ts 
from  
(select distinct user,a, b from foo) f1 
inner join foo f2 
on f2.id = 
(select id
 from foo f3 
 where f3.user=f1.user and f3.a = f1.a and f3.b=f1.b
 order by f3.ts desc
 limit 1
)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement