sqlite - 选择每个用户的最后一条消息
问题描述
我在 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 上描述了类似的问题,但我没有发现任何真正有用的东西。
解决方案
首先,获取我和其他用户之间的所有消息,并对列重新排序,以便其他用户始终位于固定列中:
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;
推荐阅读
- java - 如何在使用 SQLite 操作期间添加行?
- r - 使用 spgwr 包对来自大型栅格的数据子集运行地理加权回归
- javascript - ElementById 找到元素但不会添加事件侦听器(Chrome 扩展)
- xml - 水晶报表xml文件生成
- c++ - 错误:测试除法时需要左值作为赋值的左操作数
- java - 依赖项更改时强制类重新编译
- python - SQL:从表中选择行,其中列的每个元素都是矩阵?
- java - 运行 JUnit 测试有效,但 Gradle 测试无效。怎么修?
- c# - 如何在 Windows 注册表中输入十六进制值作为 DWORD?
- c# - 混合泛型、非泛型和基类设计问题