Jump to content

[SOLVED] Select most recent record from child table


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 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.