加入后获取群体最大价值

Get biggest value of group after join

我的数据库中有两个表:

对话:

conversationid | persone | perstwo | timestamp
1              |    1    |  3      | 1431680294000
2              |    3    |  8      | 1431680407000

留言:

messageid | conversationid | senderid | receiverid | message | timestamp     |  seen
1           1                1          3            Xyz!      1431680294000    0
2           2                3          8            Hi x!     1431680405000    0
3           2                3          8            Allt bra? 1431680407000    0

现在我想查找每个对话的最新消息。

我现在的方法只是找到用户的对话,然后尝试按对话 ID 分组:

SELECT DISTINCT conversationid, senderid, receiverid, message, timestamp 
FROM message WHERE conversationid IN
      (SELECT conversationid FROM conversation WHERE persone = 3 OR perstwo = 3)
GROUP BY conversationid ORDER BY timestamp DESC

不幸的是我得到了这些结果:

2   3   8   Hi x!   1431680405000
1   1   3   Xyz!    1431680294000

尽管我需要 Allt bra? 作为上次对话的结果。

我是 运行 Arch of MariaDB 可用的最新版本。

此类问题的常见模式是查找派生 table 中的最后一项,然后将其加入以过滤主查询。在您的情况下,查询看起来像:

select * 
from conversation c
join message m on c.conversationid = m.conversationid
join (
  select conversationid, max(timestamp) timestamp 
  from Message
  group by conversationid
) x on m.conversationid = x.conversationid
   and x.timestamp = m.timestamp
where c.persone = 3 OR c.perstwo = 3

Sample SQL Fiddle