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

时间:2019-05-07 17:01:22

标签: mysql

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

样本数据

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

我承认我正在努力做到这一点,但是我认为我需要某种高级加入,以包括来自每组电话号码的最新消息,而不管是谁发送/接收的。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

SQL DEMO

您可以像这样获得两个数字之间的最后一个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)
)               

答案 1 :(得分:1)

您可以使用“不存在”来做到这一点:

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
);

请参见demo
结果:

| 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     |