Jump to content

[SOLVED] Select most recent record from child table


Jonob

Recommended Posts

Hi all,

 

Assuming I have the following structure

 

table: company

company_id

company_name

 

table: status

status_id

company_id (FK)

status_date

description

 

How do I get all the records from company, and only the single most recent record (by status_date) from status? I want to show all fields from both tables, and if there is no record in status, then it should return nulls for each field in status.

 

Thanks for any help.

You will have to use a JOIN query:

SELECT * FROM compay JOIN status ON company.company_id=status.company_id

 

and to get the most recent record:

SELECT * FROM compay JOIN status ON company.company_id=status.company_id ORDER BY status_date LIMIT 1

 

Good luck.

 

NaCo

Just in case anyone wants to know in the future, this is what got me the right answer:

 

SELECT c.company_id, c.company_name, t1.*
FROM company c
LEFT JOIN

(select max(status_date) as date, status_id, description, company_id
from status
group by company_id) as t1 ON c.company_id = t1.company_id 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.