复杂的MySQL连接-发件人/收件人和收件人/发件人

复杂的MySQL连接-发件人/收件人和收件人/发件人,mysql,Mysql,我有一个数据库表,其中包含这样的文本消息(简化): 样本数据 id sender recipient content _____________________________________________________________________ 1 15555551111 15555552222 Hello from 1111 to 2222 2 15555552222 15555551111

我有一个数据库表,其中包含这样的文本消息(简化):

样本数据

id     sender         recipient        content
_____________________________________________________________________
1      15555551111    15555552222      Hello from 1111 to 2222
2      15555552222    15555551111      Hello from 2222 to 1111
3      15555553333    15555551111      Hello from 3333 to 1111
4      15555551111    15555554444      Hello from 1111 to 4444
5      15555551111    15555552222      It's me again
6      15555554444    15555551111      Hey 1111, it's 4444
我想要的是一起查询所有消息,以显示两个电话号码之间的最新消息,而不管是谁发送/接收消息,有点像您的手机如何将文本消息分组在一起。例如,我想查询并得到以下结果,按最近的第一个排序:

所需的查询结果

id     sender         recipient        content
_____________________________________________________________________
6      15555554444    15555551111      Hey 1111, it's 4444 
5      15555551111    15555552222      It's me again   
3      15555553333    15555551111      Hello from 3333 to 1111
我承认我对如何做到这一点有些费解,但我认为我需要某种高级加入,以包括来自每组电话号码的最新消息,而不管是谁发送/接收的。任何帮助都将不胜感激

您可以获得两个数字之间的最后一个id,如下所示:

SELECT MAX(id),
       LEAST(sender, recipient),
       GREATEST(sender, recipient)           
FROM YourTable
GROUP BY LEAST(sender, recipient), 
         GREATEST(sender, recipient)
然后,要获取最新消息:

SELECT *
FROM YourTable
WHERE id IN (    
    SELECT MAX(id) 
    FROM YourTable
    GROUP BY LEAST(sender, recipient), 
             GREATEST(sender, recipient)
)               

您可以在不存在的情况下执行此操作:

select t.*
from tablename t
where not exists (
  select 1 from tablename
  where 
    least(sender, recipient) = least(t.sender, t.recipient)
    and 
    greatest(sender, recipient) = greatest(t.sender, t.recipient)
    and 
    id > t.id
);
请参阅。
结果:


非常感谢。您不仅是第一个响应我所要查找的内容的人,而且当扩展到数十万行时,您的查询的性能也最好。你是我的英雄!谢谢你的帮助!我尝试了你的查询,但胡安·卡洛斯·奥罗佩扎的回答在我的数据中表现更好。
| id  | sender      | recipient   | content                 |
| --- | ----------- | ----------- | ----------------------- |
| 3   | 15555553333 | 15555551111 | Hello from 3333 to 1111 |
| 5   | 15555551111 | 15555552222 | It's me again           |
| 6   | 15555554444 | 15555551111 | Hey 1111, it's 4444     |