房间嵌套查询和子查询

时间:2019-10-13 04:54:21

标签: android android-room android-architecture-components

我在Android项目中使用Room,并且想编写一个复杂的查询。我搜索了一下,女巫说了一些答案,例如使用 @Embedded

class TripAndListsAndListItems {
      @Embedded
      var trip: Trip? = null

     @Relation(parentColumn = "creatorId", entityColumn = "remoteId",     entity = User::class)
     var user: List<User>? = null

     @Relation(parentColumn = "remoteId", entityColumn = "tripId", entity = PlanitiList::class)
     var lists: List<ListAndListItems>? = null
}

Here is complete article.

但是然后我必须在代码中弄清楚它,才能使用循环等提取结果。 我使用嵌套查询在 @Query 中写了查询,并使用“ as ”将具有实体字段的列匹配,如下所示:

这是 ViewModel 类:

class ServiceCard(
    val id: Int,
    val customerInfo: String,
    val time: String,
    val oilFilter: Boolean,
    val airFilter: Boolean,
    val gasFilter: Boolean,
    val oil: Boolean
)

@Doa 具有如下的 @Query 方法:

@Dao
interface ServiceCardDao :ICommonDao<ServiceCard>{

   @Query("SELECT s.services_id as id,  " +
        "s.user_mobile_no as customerInfo, " +
        "( " +
        "SELECT count(*) " +
        "FROM service_detail as sd " +
        "WHERE sd.services_id = s.services_id and sd.service_type_id = 1 " +
        ")              as oilFilter, " +
        "( " +
        "SELECT count(*) " +
        "FROM service_detail as sd " +
        "WHERE sd.services_id = s.services_id and sd.service_type_id = 2 " +
        ")         as airFilter, " +
        "( " +
        "SELECT count(*) " +
        "FROM service_detail as sd " +
        "WHERE sd.services_id = s.services_id and sd.service_type_id = 3 " +
        ")         as gasFilter,  " +
        "( " +
        "SELECT count(*) " +
        "FROM service_detail as sd " +
        "WHERE sd.services_id = s.services_id and sd.service_type_id = 4 " +
        ")         as oil, " +
        "s.service_date as time " +
        "FROM services as s ")
   fun selectAllServicesWithDetail(): LiveData<List<model.ServiceCard>>

}

这两个之间有什么优点或缺点吗?

1 个答案:

答案 0 :(得分:0)

两者都有优势。

Dao中的编码对于一个实体而言更为复杂,而另一种实体中的编码则更为复杂,但是Dao中的复杂性大于实体的复杂性差异。因此,较简单的Dao可能会赢得某些人的青睐。

因为没有后期数据检索循环来获取计数,而且由于SQLite是经过编译的C代码而不是必须解释的JVM字节码,所以这样会更高效,因此SQlite通常非常有效。但是,效率很可能是某些人为了简化编码而愿意放弃的,也许是人们习惯于放弃的。

有些人可能会考虑使用诸如DatabaseViews之类的替代方案,它将Dao和Class合并为一个。