tags:

views:

24

answers:

2

Hi,

I have two tables that look like this:

Table: cases

id
name
status
case_no

Table: notes

id
case_id
note_date
notes

I'd like to be able to create a query that grabs the data from the cases table and only the most recent entry from the notes table for each row in the cases table. So far I'm having no luck at all.

Any pointers would be greatly appreciated

+1  A: 

This will return only the cases with notes attached:

SELECT c.*,
       x.*
  FROM CASES c
  JOIN NOTES x ON x.case_id = c.case_id
  JOIN (SELECT n.case_id,
               MAX(n.note_date) AS max_note_date
          FROM NOTES n
      GROUP BY n.case_id) y ON y.case_id = x.case_id
                           AND y.max_note_date = x.note_date

If you want all cases, regardless if they have a note attached:

   SELECT c.*,
          x.*
     FROM CASES c
LEFT JOIN NOTES x ON x.case_id = c.case_id
     JOIN (SELECT n.case_id,
                  MAX(n.note_date) AS max_note_date
             FROM NOTES n
         GROUP BY n.case_id) y ON y.case_id = x.case_id
                              AND y.max_note_date = x.note_date
OMG Ponies
+1, the formatting of the queries is a thing of beauty
Adam Bernier
A: 
    SELECT *
      FROM cases c
INNER JOIN notes n ON n.case_id = c.id
                  AND n.id = (SELECT MAX(id)
                                FROM notes
                               WHERE case_id = c.id)

Also it is a common practice to keep the pointer to the last note id directly in cases table and support it with trigger

zerkms
Thanks for the lighting fast replies! Keeping the pointer to the last note in the cases table makes a lot of sense.
Simon H