I am trying to do a GROUP BY statement, with the grouped by column showing the item with the newest timestamp. However, I don’t think it’s possible to order BEFORE a GROUP BY statement. Is the following subselect the only way to do what I’m trying to accomplish?
SELECT thread_id, content, timestamp FROM
(
SELECT thread_id, content, timestamp FROM messaging_message
ORDER BY thread_id, timestamp desc
) combined
GROUP BY thread_id
Note that for a given thread_id, there may be multiple messages associated to it, and thus multiple content and timestamps for each thread_id.
If I understand correctly and you want the most recent
contentperthread_id, use aMAX()aggregate to find the timestamp, andJOINagainst it :The
ORDER BYdoesn’t come into play at all by this method. It’s all done by grouping.MySQL, unlike other RDBMS doesn’t strictly require you to have every
SELECTcolumn accounted for in theGROUP BY, so you could probably just doHowever, that isn’t portable and so I don’t recommend it. Instead, the
JOINsubquery returns the pair oftimestampandthread_id. Those are used to match up against the relatedcontentand any other columns you may need from the row. If you had a unique id on each row, you could also make a subquery which returns only the id for eachMAX(timestamp)and use it inside anIN(). But absent that unique id, a join against thethread_id, timestamppair does the job.