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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With