【问题标题】:sum() function of Sqlite does not seem to work as expected with room persistence librarySqlite 的 sum() 函数在房间持久性库中似乎无法正常工作
【发布时间】:2023-03-12 11:45:01
【问题描述】:

我想计算表中所有记录的权重字段总和,我试过了:

在道课中

@Dao
interface FooDAO {
    @Query("SELECT sum(purchaseWeight) FROM myTable")
    suspend fun calculateSumOfAllWeight(): Int    
}

在存储库类中

class FooRepository(application: Application) {

    private var fooDAO: FooDAO

    private var sumOfAllWeight = MutableLiveData<Int>()

    init {
        // skipping other code
        CoroutineScope(Dispatchers.IO).launch {
             sumOfAllWeight.postValue(fooDAO.calculateSumOfAllWeight())
        }
    }

    fun getSumOfAllWeight(): MutableLiveData<Int> {    
        Log.e("SUM_OF_WEIGHT", " sumOfAllWeight "+ sumOfAllWeight.value)
        return sumOfAllWeight    
    }    
}

但它会打印出来

E/SUM_OF_WEIGHT: sumOfAllWeight null

在 logcat 中,我提到了 This Link 在 sqlite 中使用 sum()。

更新

我已经搜索并找到了thisthisSO 的帖子并更新了

@Query("SELECT sum(purchaseWeight) as value FROM myTable")
suspend fun calculateSumOfAllWeight(): Int

发现This并更新

@Query("SELECT COALESCE(sum(COALESCE(purchaseWeight,0)), 0) From myTable")
suspend fun calculateSumOfAllWeight(): Int

但仍然返回相同的null

【问题讨论】:

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


    【解决方案1】:

    当表为空时,sql 中的聚合函数返回 null。只有 COUNT 函数返回 0。您还读取了异步更新的 LivaData 的值,并且您不确定查询是否已经执行。尝试在挂起函数之后的init块中放置一个日志来测试返回值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 2012-05-06
      • 2013-02-17
      相关资源
      最近更新 更多