简体   繁体   中英

Select distinct values based on a column with maximum date value from second column

The title is a bit complex. I apologize but the query is also complex for a non-SQL person.

I have a table messages that has the following structure:

Message(id, sender_id, receiver_id, message_datetime)

My goal is to select the last messages received by a receiver_id from distinct senders.

When I do for example:

SELECT * 
FROM  `message` 
WHERE  `receiver_id` =1

I get something like:

1005  |   2    |    1    |  2015-11-08
1004  |   3    |    1    |  2015-11-07
1003  |   3    |    1    |  2015-11-06
1002  |   2    |    1    |  2015-11-05 
1001  |   2    |    1    |  2015-11-04

While I need something like:

1005  |   2    |    1    |  2015-11-08
1004  |   3    |    1    |  2015-11-07

Your usual expert guidance is highly appreciated. I am really stuck with such a query. Thanks again and sorry for the bad formatting.

You need to create a subquery that returns the maximum message id by sender_id for a given receiver and join it to the messages table to get all other fields:

SELECT m.* 
FROM  `message` AS m
INNER JOIN (SELECT sender_id, MAX(message_date) as md
                FROM message WHERE  `receiver_id` =1 GROUP BY sender_id) AS t
ON m.message_date=t.md and m.sender_id=t.sender_id
WHERE  `receiver_id` =1
    Select * from (
           Select * from `Message` where receiver_id=1 order by message_datetime desc
) a group by a.sender_id

This query first orders the data by date and then it group by sender_id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM