SELECT最后一个接收者的最后消息。 MySQL的

时间:2017-12-25 18:22:43

标签: mysql sql

我的表

id|receiver|sender|content|time
1 |   6    |  2   |  a    | 13:33
2 |   4    |  3   |  b    | 13:35
3 |   4    |  3   |  c    | 14:01
4 |   5    |  3   |  d    | 14:03
5 |   7    |  2   |  e    | 14:05
6 |   4    |  3   |  f    | 14:07

我的预期结果: -

id|receiver|sender|content|time
6 |   4    |  3   |  f    | 14:07
3 |   4    |  3   |  c    | 14:01
2 |   4    |  3   |  b    | 13:35

目前我的做法是: -

SELECT * FROM `meassages`
  WHERE `sender` = 3 AND `receiver` IN (
    SELECT `receiver` FROM `messages` ORDER BY `time` DESC LIMIT 1
  ) ORDER BY `time` DESC

我希望比我的方法更容易做到这一点。我知道这是可能的。但我尽我所能。感谢先进的任何帮助。

2 个答案:

答案 0 :(得分:1)

虽然您的查询似乎很好,但它假定最后一条消息来自sender = 3。因此,最好在子查询中使用where

SELECT m.*
FROM messages m
WHERE m.sender = 3 AND 
      m.receiver = (SELECT m2.receiver
                    FROM messages m2
                    WHERE m2.sender = m.sender
                    ORDER BY m2.time DESC
                    LIMIT 1
                   )
ORDER BY m.time DESC;

使用=而不是IN强调子查询返回一行。另外,我添加了表别名和限定列名。

答案 1 :(得分:0)

请改为尝试:

SELECT m1.* 
FROM `meassages` AS m1
INNER JOIN
(
   SELECT receiver, MAX(time) AS LatestTime
   FROM messages 
   group by receiver
) AS m2  ON m1.receiver = m2.receiver 
        AND m1.`time` = m2.LatestTime
WHERE m1.`sender` = 3;

内部查询,将为您提供每个接收器的最新时间,这应该是最后一个接收器。然后根据最新时间再次加入表格,您将删除除最新时间之外的所有行。