如何按唯一用户ID分组并按最新消息ID排序?

时间:2018-10-06 18:49:04

标签: mysql sql

我的消息表

message_id | message_body_content | sender_user_id | receiver_user_id
1          | hello world          | 1000           | 1200
2          | hello world 2        | 1001           | 1200
3          | hello world again    | 1000           | 1200
4          | xyz                  | 1001           | 1200
5          | abc                  | 1200           | 1999

我想按自己的message表按sender_user_id唯一和最后message_id分组

所以输出应该像;

message_id | message_body_content | sender_user_id | receiver_user_id
3          | hello world again    | 1000           | 1200
4          | xyz                  | 1001           | 1200

因为message_id的最新sender_user_id是IS3。从理论上讲。

当我尝试

SELECT * FROM message WHERE receiver_user_id = 1200 
GROUP BY sender_user_id
ORDER BY message_id DESC

它没有用。因为MySQL首先按message_id(最小message_id值)分组

然后排序。

如何通过最大message_id来获得唯一的发件人消息

3 个答案:

答案 0 :(得分:1)

select message_id, message_body_content, sender_user_id, receiver_user_id
from message t
where t.message_id = (select max(t1.message_id)
                      from message t1
                      where t1.sender_user_id = t.sender_user_id
                     )
order by message_id;

答案 1 :(得分:0)

我认为您不想“分组”。您要过滤。所以,我想你想要

SELECT m.*
FROM message m
WHERE m.receiver_user_id = 1200 AND
      m.message_id = (SELECT MAX(m2.message_d)
                      FROM message m2
                      WHERE m2.receiver_user_id = m.receiver_user_id AND
                            m2.sender_user_id = m.sender_user_id 
                     )
ORDER BY m.message_id DESC;

答案 2 :(得分:0)

您可以使用子查询

select m.* from message m
where (m.message_id,m.sender_user_id) in(
SELECT max(message_id) as message_id ,sender_user_id
 FROM message  
GROUP BY sender_user_id
 ) and m.receiver_user_id = 1200
ORDER BY m.message_id DESC