仅获取基于ID的最后一条记录

我正在构建聊天应用程序,我只想按用户显示最后记录 就像我发送了1000封邮件,但是我只和10个人聊天,那么我需要获取10个人的名字和最后一封邮件,无论他们是发给我还是我最后发给他们

仅获取基于ID的最后一条记录

请参见上表,并提供解决方案,例如我只希望从最后两个记录中仅获取一个记录。

tmc19850121 回答:仅获取基于ID的最后一条记录

您可以使用相关子查询进行过滤:

select t.*
from mytable t
where created = (
    select max(created)
    from mytable t1
    where t1.m_from = t.m_from and t1.m_to = t.m_to
)

这只会给您每个(m_from,m_to)元组的最新消息(根据存储在created列中的日期)。

如果您想要每个(m_from,m_to) (m_to,m_from)的最新消息,则:

select t.*
from mytable t
where created = (
    select max(created)
    from mytable t1
    where 
        (t1.m_from = t.m_from and t1.m_to = t.m_to)
        or (t1.m_from = t.m_to and t1.m_to = t.m_from)
)
本文链接:https://www.f2er.com/3132716.html

大家都在问