【问题标题】:how to use where keyword in roomdb query如何在 roomdb 查询中使用 where 关键字
【发布时间】:2020-10-05 13:40:38
【问题描述】:
@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 没有查看播放列表表

【问题讨论】:

  • 也许user.playlistName = quran
  • @Andrew 不是这样
  • 在您的第二个查询中,您正在询问具有播放列表名称的用户。无论如何,这将如何运作?如果您是新编码员,则需要了解查询数据库的基础知识。你能解释一下你想要达到的目标吗?所以我可以帮你。

标签: android kotlin


【解决方案1】:

我觉得这很有用

data class UserWithPlaylists(
        @Embedded val playlists: Playlist,

        @Relation(
                parentColumn = "userCreatorId",
                entityColumn = "userId"
        )       val user: User

)

这很好用

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

但是roomdb 有两张桌子太糟糕了,你不能这样做

@Query("SELECT * FROM Playlist where playlistName=quran and age=3")
            fun getUsersWithPlaylists(): List<UserWithPlaylists> 

where关键字只使用一个表列。

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

    • 我问的不是 sqlight 而是 roomdb
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 2021-09-08
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多