首页 > 解决方案 > 如何在 roomdb 查询中使用 where 关键字

问题描述

@Entity
data class User(
    @PrimaryKey val userId: Long,
    val name: String,
    val age: Int
)

@Entity
data class Playlist(
    @PrimaryKey val playlistId: Long,
    val userCreatorId: Long,
    val playlistName: String
)

ata class UserWithPlaylists(
    @Embedded val user: User,
    @Relation(
          parentColumn = "userId",
          entityColumn = "userCreatorId"
    )
    val playlists: List<Playlist>
)

@Transaction
@Query("SELECT * FROM User")
fun getUsersWithPlaylists(): List<UserWithPlaylists>

这个例子来自https://developer.android.com/training/data-storage/room/relationships ,我的问题

如果我只想让用户年龄=10

    @Query("SELECT * FROM User where age=10")
    fun getUsersWithPlaylists(): List<UserWithPlaylists> 

但如果我想要 playlistName ="quran"

@Query("SELECT * FROM User where playlistName=quran")
        fun getUsersWithPlaylists(): List<UserWithPlaylists> 

不能这样做,因为roomdb看不到播放列表表

标签: androidkotlin

解决方案


Join您需要的功能在 SQL 数据库中调用。我建议您使用一些教程来学习。这是根据您的结构的答案。

SELECT `user`.`UserId`,`user`.`name`,`user`.`age` From `user` INNER JOIN `playlist` On `playlist`.`userCreatorId`=`user`.`UserId` WHERE `playlist`.`playlistName`='Use your playlist name here'

这里有一篇关于Join.

https://www.w3schools.com/sql/sql_join.asp


推荐阅读