在 Android 中将 MySql 查询转换为 SQL Room 查询 - kotlin
Posted
技术标签:
【中文标题】在 Android 中将 MySql 查询转换为 SQL Room 查询 - kotlin【英文标题】:Converting MySql Query to SQL Room query in Android - kotlin 【发布时间】:2021-08-24 14:01:24 【问题描述】:我刚刚从后端获得了以下 mysql 查询。 我必须使用 android 中的 Room 数据库在本地管理这些东西。
所以,后端的查询如下:
Select DATE_FORMAT(timeStamp ,'%d-%b') AS date, DATE_FORMAT(timeStamp ,'%d') AS dateNumber,
ROUND(AVG(IF(stateOfCharge IS NULL, 0, stateOfCharge)), 2) AS chargeOverTime,
ROUND(AVG(IF(temperature IS NULL, 0, temperature)), 2) AS temperature,
ROUND(AVG(IF(current IS NULL, 0, current)), 2) AS averageChargeDischarge
from batteryDetails
where name="VERNE000003"
and timeStamp between "2021-03-11 11:40:29" AND "2021-03-12 23:40:29"
Group by DATE_FORMAT(timeStamp ,"%Y-%m-%d") ORDER BY timeStamp;
我尝试购买转换如下:
@Query("SELECT datetime(timeStamp ,'%d-%b') AS date, " +
"datetime(timeStamp ,'%d') AS dateNumber, " +
"ROUND(AVG(if(stateOfCharge IS NULL, 0, stateOfCharge)), 2) AS chargeOverTime, " +
"ROUND(AVG(if(temperature IS NULL, 0, temperature)), 2) AS temperature, " +
"ROUND(AVG(if(current IS NULL, 0, current)), 2) AS averageChargeDischarge " +
"FROM " + DatabaseConstant.mUserBatteryDetailsTable +
" WHERE name= :batteryId and timeStamp between :startDate AND :endDate " +
"GROUP BY datetime(timeStamp ,'%Y-%m-%d') ORDER BY timeStamp")
suspend fun getHistoryData(batteryId: String, startDate: String, endDate: String): List<BatteryDetails>?
但出现以下错误:
错误:查询有问题:[SQLITE_ERROR] SQL 错误或 缺少数据库(没有这样的功能:如果) 公共抽象 java.lang.Object getHistoryData(@org.jetbrains.annotations.NotNull()
【问题讨论】:
用 CASE 替换 IF()。 @Akina 谢谢妈妈,现在得到:“SQL 错误或缺少数据库(靠近“)”:语法错误)“请。指导。IF(A,B,C)
=> CASE WHEN A THEN B ELSE C END
。但在您的情况下,IF(column IS NULL, 0, column)
可以替换为COALESCE(column, 0)
。
IF(stateOfCharge IS NULL, 0, stateOfCharge)
在任何数据库(Access 除外)中的等价物是COALESCE(stateOfCharge, 0)
【参考方案1】:
查询解决如下:
@Query("Select strftime('%d %m',datetime(timeStamp, 'unixepoch')) as dates, " +
"strftime('%d', datetime(timeStamp, 'unixepoch')) as dateNumber, " +
"round(avg(coalesce( stateOfCharge,0))) as chargeOverTime, " +
"ROUND(AVG(coalesce( avgTemperature,0))) as avgTemperature, " +
"ROUND(AVG(coalesce(current,0))) as averageChargeDischarge " +
"FROM " + DatabaseConstant.mUserBatteryDetailsTable +
" WHERE name= :batteryId and timeStamp between :startDate AND :endDate " +
"Group by datetime(timeStamp ,'%Y-%m-%d') ORDER BY timeStamp")
【讨论】:
以上是关于在 Android 中将 MySql 查询转换为 SQL Room 查询 - kotlin的主要内容,如果未能解决你的问题,请参考以下文章
在查询中将 DateTime.Ticks 转换为 MySQL DateTime
在 csv_from_result 方法中将 mysql 时间戳转换为我们在 codeigniter 查询对象中的日期