从每个对话sql获取最后一条消息

时间:2015-05-17 09:56:14

标签: sql greatest-n-per-group

我在sql中有一个消息表,它基本上是当前用户的列,他正在与之交互的用户,id和消息的内容。我需要从每个不同的对话中检索最后一条消息,以便进行预览。

任何想法如何?

2 个答案:

答案 0 :(得分:0)

使用NOT EXISTS读取该会话中没有后续消息的所有行。类似的东西:

select *
from messages m1
where not exists (select 1 from messages m2
                  where m2.messageid > m1.messageid
                    and m1.conversationid = m2.conversationid)

示例输出:

SQL>create table messages (conversationid int, messageid int);
SQL>insert into messages values (1,1);
SQL>insert into messages values (1,2);
SQL>insert into messages values (2,1);
SQL>insert into messages values (2,2);
SQL>insert into messages values (2,3);
SQL>insert into messages values (3,1);
SQL>select *
SQL&from messages m1
SQL&where not exists (select 1 from messages m2
SQL&                  where m2.messageid > m1.messageid
SQL&                    and m1.conversationid = m2.conversationid);
conversationid   messageid
============== ===========
             1           2
             2           3
             3           1

                  3 rows found

答案 1 :(得分:0)

每组最大问题通常使用modern SQL使用窗口函数来解决:

select *
from (
  select c.*,
         row_number() over (partition by conversation_id order by message_time desc) as rn
  from conversation c
) t
where rn = 1
order by conversation_id;