Android SQLite:加入和光标

时间:2014-05-28 07:09:15

标签: android sqlite join database-cursor

我在sqlite数据库中有以下表格:

items
______
 _id (PK)
name
section_subsection_id (FK)

section_subsections
______
_id (PK)
section_id (FK)
subsection_id (FK)

subsections
______
_id (PK)
name

sections
______
_id (PK)
name

我想向子部分提供某个关键字,该关键字只会抓取与限制下的此关键字匹配的关键字,例如x,并计算所有部分子部分匹配。

我使用了几个查询,这里有一个:

String selectQuery = "Select subsections.name, subsections._id, temp.count as count 
FROM subsections LEFT JOIN 
sections_subsections ON subsections._id = sections_subsections.subsection_id 
JOIN items (SELECT count(items._id) as count from items) temp 
ON items.section_subsection_id = sections_subsections._id 
WHERE subsections.name LIKE 'keyword' AND sections_subsections.section_id = 1 ORDER BY
subsections.name ASC LIMIT 50 OFFSET 0 ";

当我尝试迭代结果时,我得到与关键字搜索匹配的列表,但 count 始终显示结果集中的最后一个计数值。当我在sqlite shell中运行原始查询时,我在列中看到了具有相应行的正确计数,但是在Android / Java中迭代光标似乎有问题。或者可能是我的查询?

因此对于应用程序中的ListView,我会获得相同的计数(即全部为20),但在shell中我看到 count 具有正确的值。实际上,在游标迭代期间,如果我将Log.d count 添加到屏幕,它也全部为20,但是其他列值 name 是不同的。我的查询有什么问题?或者我如何正确迭代具有多个连接的表?

_id  name    count 
 ---------------   
1    item1   79
2    item2   30
3    item3   20

编辑: 我在Java中做了类似的事情:

Cursor cursor = sqliteDatabase.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}

if (cursor.moveToFirst()) {
do {
SubSection subSection = new SubSection();                      
subSection.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));                     subSection.setSubSectionName(cursor.getString(cursor.getColumnIndex(KEY_TABLE_SUBSECTIONS_SUBSECTION_NAME)));
subSection.setRecords(cursor.getColumnIndex("count"));
subSections.add(subSection);
}
while 
(cursor.moveToNext());
}

2 个答案:

答案 0 :(得分:1)

尝试以下查询

Select subsections.name, subsections._id, (SELECT count(items._id) from items WHERE items.section_subsection_id = sections_subsections._id) as count 
FROM subsections LEFT JOIN 
sections_subsections ON subsections._id = sections_subsections.subsection_id 
WHERE subsections.name LIKE 'keyword' AND sections.name = 'Category' ORDER BY
subsections.name ASC LIMIT 50 OFFSET 0 ";

答案 1 :(得分:0)

感谢Syed Waqas,你的回答是正确的。问题实际上不是我的疑问。这是我的光标。我应该使用:cursor.getInt(cursor.getColumnIndex("count"))而不是我原来的问题。我不知道自己怎么没注意到这个大错误。对于其他人,您可以使用可爱的DatabseUtils调试光标。 :)

Log.d(LOG, "ROW: " + DatabaseUtils.dumpCursorToString(cursor));