Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show only most recent date from joined MySQL table

Tags:

sql

join

mysql

I have 2 tables, a "document" table and a "content" table. They look like this (simplified):

document table:
docID
docTitle

content table:
contentID
docID
dateAdded
content

For every content change, a new record is inserted into the "content" table. This way there is a complete history of all changes. I would like to get a list of all the documents, with the latest content joined. It should return the docID, docTitle, and the associated content record with the newest "dateAdded" value. My brain is failing me right now, how would I create this join?

like image 779
Jon Tackabury Avatar asked Sep 02 '09 15:09

Jon Tackabury


Video Answer


2 Answers

This can be done with a subquery:

SELECT d.docID, docTitle, c.dateAdded, c.content
FROM document d LEFT JOIN content c ON c.docID = d.docID
WHERE dateAdded IS NULL
    OR dateAdded = (
        SELECT MAX(dateAdded)
        FROM content c2
        WHERE c2.docID = d.docID
    )

This is known as a "groupwise maximum" query

Edit: Made the query return all document rows, with NULLs if there is no related content.

like image 70
Christian Oudard Avatar answered Oct 24 '22 12:10

Christian Oudard


Use:

SELECT t.docid, 
       t.docTitle, 
       mc.dateAdded, 
       mc.content
  FROM DOCUMENT t
  JOIN (SELECT c.docid,
               c.content,
               MAX(c.dateAdded)
          FROM CONTENT c
      GROUP BY c.docid, c.content) mc ON mc.docid = t.docid 
                                     AND mc.dateadded = t.dateadded

This should be faster than a correlated subquery.

Alternative for when there are no content records for a document:

   SELECT t.docid, 
          t.docTitle, 
          mc.dateAdded, 
          mc.content
     FROM DOCUMENT t
LEFT JOIN (SELECT c.docid,
                  c.content,
                  MAX(c.dateAdded)
             FROM CONTENT c
         GROUP BY c.docid, c.content) mc ON mc.docid = t.docid 
                                     AND mc.dateadded = t.dateadded
like image 4
OMG Ponies Avatar answered Oct 24 '22 11:10

OMG Ponies