首页 > 解决方案 > 选择每个用户的最后一条消息

问题描述

我在 android 中有一个 SQLite 表,其中包含如下消息:

@primarykey
long id;
String from;
String to;
long timestamp;
String body;

在此表中,我和其他用户在一对一聊天中的所有消息。我需要一个选择,它将返回我和每个用户之间的最后一条消息。我知道如何获得所有不同的地址,合并它们并为每个单独选择最后一条消息,但我需要更好的方法 - 一步完成

    @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH)
    @Query("SELECT DISTINCT `from`, `to` FROM Message")
    LiveData<List<ChatHelper>> getDinstinctChats();

    @Query("SELECT * FROM Message where `from` LIKE :address OR `to` LIKE :address ORDER BY `timestamp` LIMIT 1")
    LiveData<List<ChatMessage>> getLastMessageWith(String address);

stackoverflow 上描述了类似的问题,但我没有发现任何真正有用的东西。

标签: sqliteselectandroid-sqlite

解决方案


首先,获取我和其他用户之间的所有消息,并对列重新排序,以便其他用户始终位于固定列中:

SELECT id, `from` AS other, timestamp, body
FROM Message
WHERE `to` LIKE :address
UNION ALL
SELECT id, `to`   AS other, timestamp, body
FROM Message
WHERE `from` LIKE :address;

然后按“其他”列分组以获得每个用户的一个结果行:

SELECT *, max(timestamp)
FROM (SELECT id, `from` AS other, timestamp, body
      FROM Message
      WHERE `to` LIKE :address
      UNION ALL
      SELECT id, `to`   AS other, timestamp, body
      FROM Message
      WHERE `from` LIKE :address)
GROUP BY other;

推荐阅读