首页 > 解决方案 > 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);
}

所以,但我想用一个查询来做到这一点,而不是使用这个循环。

标签: javaandroidsqlsqliteandroid-room

解决方案


您需要将查询重写如下

SELECT 
  *, 
  (
    (
      SELECT 
        COUNT(*) 
      FROM 
        (
          SELECT 
            content_uid 
          FROM 
            content 
          WHERE 
            content_uid = postUid 
            AND contentTime > : aWeekAgo
        )
    )> 0
  ) AS userHasNewContent 
FROM 
  posts

推荐阅读