Let's say I have a table called messages
with the columns:
id | from_id | to_id | subject | message | timestamp
I want to get the latest message from each user only, like you would see in your FaceBook inbox before you drill down into the actual thread.
This query seems to get me close to the result I need:
SELECT * FROM messages GROUP BY from_id
However the query is giving me the oldest message from each user and not the newest.
I can't figure this one out.
The group by will always return the first record in the group on the result set. SELECT id, category_id, post_title FROM posts WHERE id IN ( SELECT MAX(id) FROM posts GROUP BY category_id ); This will return the posts with the highest IDs in each group.
Retrieving the last record in each group using GROUP BY There are two solutions explained here using the GROUP BY clause. In both these solutions, we will be using the MAX() function to get the maximum value of id and then retrieving the other columns corresponding to this maximum id.
GROUP BY only treats two rows as duplicates if all the column values in both the rows are the same. If even a single column value in either of the row is non-matching, they are treated as unique.
To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.
You should find out last timestamp
values in each group (subquery), and then join this subquery to the table -
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;
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