Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the latest record in each group using GROUP BY? [duplicate]

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.

like image 560
user1019144 Avatar asked Jun 12 '12 15:06

user1019144


People also ask

How do you GROUP BY and get the latest record in SQL?

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.

How do I get the latest record of each ID in SQL?

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.

Does GROUP BY allow duplicates?

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.

How do you SELECT a single record for duplicate rows in SQL?

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.


1 Answers

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; 
like image 86
Devart Avatar answered Sep 30 '22 02:09

Devart