java - SQLite:如何从 subQuery 填充 pojo 上的布尔字段
问题描述
我想返回一个类似的帖子列表。
@Query("SELECT * FROM posts")
List<Post> getPosts()
我有一个pojo。
post {
name:String
id :String
postUid:String
userHasNewContent:Boolean
}
现在,我希望列表中的每个帖子都有userHasNewContent:Boolean
,通过检查拥有该帖子的用户是否有新内容(不超过一周)来填充
所以我尝试了。
@Query("SELECT *,
(SELECT content_uid FROM content WHERE content_uid = postUid AND
contentTime < :aWeekAgo)AS userHasNewContent
FROM posts")
List<Post> getPosts(String aWeekAgo)
WHERE content is: content{ contentTime:Long //Unix Timestamp id:String }
和
public static Long aWeekAgo() {
long day = (1000 * 60) * 60 * 24;
return System.currentTimeMillis() - day * 7;
}
这似乎没有按预期工作,我是这样做的吗?
编辑 好的,写完问题后,现在很清楚我想要做什么。这是简短的版本。
//Get all posts
@Query("SELECT * FROM posts")
List<Post> getPosts()
//Then loop through them.
@Query("SELECT count(*) FROM content WHERE contentId :contentUID AND soundTime < : aWeekAgo")
int checkIfUserHasNewContent(String uid, long aWeekAgo);
List<Post> postsWithNewContentIndicator = new ArrayList<>();
for (Post post : postsFromDb) {
post.userHasNewContent(checkIfUserHasNewContent(post.getUid()) > 0);
postsWithNewContentIndicator.add(post);
}
所以,但我想用一个查询来做到这一点,而不是使用这个循环。
解决方案
您需要将查询重写如下
SELECT
*,
(
(
SELECT
COUNT(*)
FROM
(
SELECT
content_uid
FROM
content
WHERE
content_uid = postUid
AND contentTime > : aWeekAgo
)
)> 0
) AS userHasNewContent
FROM
posts
推荐阅读
- python - on_member_join 和删除不起作用。如何让它发挥作用?
- android - Mono.AndroidTools.AdbException:尝试读取流的末尾(在 Visual Studio 上)
- java - 如何创建一个元素少于给定数组的新数组?
- javascript - webpack5 output.library 无法导入
- angular - 扩充 OktaAuthService 打字稿模块时无法编译
- sql - SQLite 在 strftime 上给出负值
- javascript - 如何使用javascript从html表中删除firebase数据库节点?
- java - 如何保护 try with resources 语句之外的变量?
- regex - Notepad ++:在其他字符之前重新替换出现的字符
- postgresql - 尝试使用 SOH 作为从 AWS S3 导入 postgres 表的分隔符