在我的数据库中,有两个表,
1)任务:(id(INTEGER + PRIMARY_KEY),title,description,timestamp,category_id(Category的外键 - > id))
2)类别:(id(INTEGER + PRIMARY_KEY),名称)
要从表格中选择数据,Anko正在提供如下方法:
var mDatabase: DatabaseManager = DatabaseManager.getInstance(activity)
var mResult: List<TaskModel> = ArrayList()
mDatabase.use {
mResult = select(TABLE_TASK).parseList(classParser())
}
我想要的是显示具有类别名称的任务列表 我已经检查了所有教程和堆栈链接,但没有任何方法来实现这一点。
有没有办法从Kotlin Anko的两个表中选择数据?
谢谢你的进步!
答案 0 :(得分:3)
它已经晚了但对我这样的人有用
简而言之,答案是肯定的
你应该创建一个包含连接列数据变量的数据类,如下所示:
data class joinTable(val id: Int, val title: String, val name:String)
并在select命令中使用内连接
database.use {
select("table1 inner join table2",
"id,title,name").exec { parseList<joinTable>(classParser()) }
}
它是
答案 1 :(得分:0)
我也在这里发布了另一个问题的答案(请参阅https://github.com/Kotlin/anko/issues/622)。我试图在Anko SQLite中进行查询,该查询在同一个表的两次使用内连接(例如SELECT ... FuelData AS FuelData1 INNER JOIN FuelData AS FuelData2 ON FuelData1.Id = FuelData2.Id)。
我添加了一个数据类:
class FuelData2(
val id : Int,
val currentDate: String,
val litersPer100Km: Double
)
并将逻辑添加到我的活动类:
private fun readFuelData2(): ArrayList<FuelData2> {
val resultList = ArrayList<FuelData2>()
val query = "SELECT FuelData1.Id, FuelData2.CurrentDate," +
" (FuelData2.Fueled / (FuelData2.Mileage - FuelData1.Mileage) * 100) AS LitersPer100Km" +
" FROM FuelData AS FuelData1" +
" INNER JOIN FuelData AS FuelData2" +
" ON FuelData1.Id = (FuelData2.Id - 1);"
database.use {
val cursor = database.writableDatabase.rawQuery(query, null)
while (cursor.moveToNext()) {
val fuelData = FuelData2(id = cursor.getInt(0),currentDate = cursor.getString(1),
litersPer100Km = cursor.getDouble(2))
resultList.add(fuelData)
}
}
return resultList
}
我想要的查询是:
SELECT FuelData1.Id, FuelData2.CurrentDate,
(FuelData2.Fueled / (FuelData2.Mileage - FuelData1.Mileage) * 100) AS LitersPer100Km
FROM FuelData AS FuelData1
INNER JOIN FuelData AS FuelData2
ON FuelData1.Id = (FuelData2.Id - 1);
我为Anko创建了另一个问题,即在文档中添加一个示例,因为它真的令人困惑:https://github.com/Kotlin/anko/issues/623