获取MySQL数据库中两个人之间的最后一次通信数据

时间:2015-04-21 17:03:02

标签: mysql

想象一下,我们在用户

之间有一条table的关注消息
sender-id    receiver_id       mssg   
-----------------------------------
1               2               m1
1               3               m2
2               1               m3
1               4               m4
4               1               m5
4               2               m6
4               1               m7

我想要在MySQL中与其他人讨论用户的结果 和聊天应用程序一样 对于用户1,我们应该

[mssg chat counter]       chat with user id       last mssg
   ------------------------------------------------------
2                            2                          m3
1                            3                          m2
3                            4                          m7

2 个答案:

答案 0 :(得分:1)

如果您有idUNIQUE AUTO_INCREMENT,则可以使用此查询:

http://sqlfiddle.com/#!9/17a9f/7

SELECT m1.*, m.mssg
FROM (
  SELECT IF(messagies.sender_id=1, messagies.receiver_id,messagies.sender_id) as opponent,
    COUNT(*), MAX(messagies.id) id
  FROM messagies
  WHERE messagies.sender_id=1 
    OR messagies.receiver_id=1
  GROUP BY opponent ) m1

LEFT JOIN messagies m
ON m.id  = m1.id

答案 1 :(得分:-1)

您希望GROUP BYsender_idreceiver_id,并获得最多timestamp列的行。

SELECT sender_id, receiver_id, mssg AS last_mssg, MAX(timestamp)
FROM messages
GROUP BY sender_id, receiver_id;

通过在查询中指定MAX(timestamp),MySQL只会在将其编译为GROUP BY时获取匹配的行,从而方便地获得所需的结果。