views:

172

answers:

2

I have two tables named foo and bar, hypothetically speaking.

foo has columns foo_id, foo_fluff bar has columns bar_id, foo_id, timestamp

I need a query which will retrieve return one row for any foo_id that the table bar contains, with the latest timestamp.

So, if bar has three rows, two of which have a foo_id of 1, and 1 of which has foo_id 2, it'll return 2 rows. For foo_id 1 it'll return the row which has the greater timestamp of the two rows.

A: 
SELECT timestamp FROM bar GROUP BY foo_id ORDER BY timestamp DESC

Just join the foo table on foo_id if you want to select the data from the foo table

jjclarkson
+1  A: 

I think this is what you are looking for (unless it must be a subquery and not a join)

select max(bar.timestamp), foo.foo_fluff 
 from foo
 inner join bar
          on foo.foo_id = bar.foo_id
 group by foo.foo_fluff
DanSingerman