Retrieving the Most Recent Records Per Group with GROUP BY
In this context, you have a table named "messages" with the columns "id", "from_id", "to_id", "subject", "message", and "timestamp". Your goal is to extract the most recent message from each user, akin to the display in a Facebook inbox.
The query provided, "SELECT * FROM messages GROUP BY from_id", yields the oldest message for each user instead of the latest. To rectify this, an alternative approach is required.
To obtain the most recent messages, you need to determine the maximum timestamp for each user and join this information with the "messages" table. The query below accomplishes this:
SELECT t1.* FROM messages t1 JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2 ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;
This query performs the following:
The result is a table containing only the most recent messages for each user, providing the desired functionality.
The above is the detailed content of How to Retrieve the Most Recent Message from Each User in a Database?. For more information, please follow other related articles on the PHP Chinese website!