According to this answer, the best way to get the latest record in each group is like this:
SELECT m1.*
FROM messages m1
LEFT JOIN messages m2 ON (m1.name = m2.name AND m1.id < m2.id)
WHERE m2.id IS NULL
I have tried this and it works great.
However, I also need to check whether the latest record is the only record in the group. I tried modifying the query to this:
SELECT m1.*, COUNT(m3.name)
FROM messages m1
LEFT JOIN messages m2 ON (m1.name = m2.name AND m1.id < m2.id)
LEFT JOIN messages m3 ON m1.name = m3.name
WHERE m2.id IS NULL
But it only returns one row.
If I remove the COUNT()
statement, leaving us with this:
SELECT m1.*
FROM messages m1
LEFT JOIN messages m2 ON (m1.name = m2.name AND m1.id < m2.id)
LEFT JOIN messages m3 ON m1.name = m3.name
WHERE m2.id IS NULL
Duplicate rows are returned, so apparently the additional LEFT JOIN
messes up the query.
Is there a simple way to check whether the latest record returned is the only record in the group? A simple bool value would be fine, or the number of records in the group would work, too.
EDIT: The reason I'm trying to do this is that I'm writing a commenting system and I want users to be able to edit comments. When a comment is edited, I want to display a link showing it was edited that, when clicked, takes you to a page showing the edits (like on facebook, or how the revision system works for questions on stackoverflow). So I need to get the latest revision of each comment, as well as an indicator letting me know whether there are multiple revisions of the comment (so I know whether or not to show an "edited" link). The solution needs to be efficient, since there might be hundreds of comments in a thread.