简体   繁体   English

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

[英]SELECT Last messages from last receiver. mysql

My table 我的桌子

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

My expected result:- 我的预期结果:

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

Currently my approach:- 目前我的方法:

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

Is there an easier method? 有没有更简单的方法?

Although your query is seemingly fine, it assumes that the last message was from sender = 3 . 尽管您的查询看起来不错,但它假定最后一条消息来自sender = 3 So, it is better to have a where in the subquery: 因此,最好在子查询中有一个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;

Using = instead of IN emphasizes that the subquery returns one row. 使用=代替IN强调子查询返回一行。 Also, I added table aliases and qualified column names. 另外,我添加了表别名和限定的列名。

Try this instead: 尝试以下方法:

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;

The inner query, will give you the latest time for each receiver, this should be the last receiver. 内部查询将为您提供每个接收者的最新时间,这应该是最后一个接收者。 Then with joining the table again based on this latest time you will remove all the rows except those with the latest time. 然后,根据最近的时间再次加入该表,您将除去所有具有最新时间的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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