根据第二列中具有最大日期值的列选择不同的值 [英] Select distinct values based on a column with maximum date value from second column
问题描述
标题有点复杂.我很抱歉,但对于非SQL用户来说,查询也很复杂.
The title is a bit complex. I apologize but the query is also complex for a non-SQL person.
我有一个表messages
,该表具有以下结构:
I have a table messages
that has the following structure:
消息(id,发送方ID,接收方ID,消息日期时间)
Message(id, sender_id, receiver_id, message_datetime)
我的目标是选择receiver_id
从不同发件人处收到的最后一封邮件.
My goal is to select the last messages received by a receiver_id
from distinct senders.
例如,当我这样做时:
SELECT *
FROM `message`
WHERE `receiver_id` =1
我得到类似的东西:
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.
推荐答案
您需要创建一个子查询,该子查询通过sender_id返回给定接收者的最大消息ID,并将其加入到message表中以获取所有其他字段:>
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
这篇关于根据第二列中具有最大日期值的列选择不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!