• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

SQL (mysql) - How do I construct query to sort and limit join results?

aceO07

Diamond Member
I have 2 tables. Table A stores records, table B stores updates to table A.

In table A, there would be fields: id, name.
In table B, there would be fields: a_id, name, updated_at.

Any record in table A may have any number of related records in table B.

What sql query do I need to get records from table A, along with only the latest related update record from table B? (The idea is to get the latest updated_at value from table B for the associated record.)

This query
Code:
SELECT a.*, b.updated_at from a left outer join b on a.id = b.a_id group by a.id
unfortunately does not return the latest record from table B. Even adding in an order to the query does not work. Any ideas?
 
Shot in the dark, can't remember if MySQL can do table definitions on the fly..

Code:
select a.*,c.updated_at
from a
 left outer join (
      select a_id, max(updated_at) updated_at from b group by a_id
 ) c on (a.id=c.a_id)
group by a.id

I think you can also put a "where b.id=a.id" in the "max table"..
 
Last edited:
Thanks Ka0t1x! That did the trick.

There's actually no need to do the last 'group by a.id' since it's already been grouped.
 
Back
Top