【发布时间】:2014-05-28 07:09:14
【问题描述】:
我在一个 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
我想为 subsections 提供一个特定的关键字,它只会抓取那些在某个限制(例如 x)下与该关键字匹配的关键字,并计算下的所有 items这 section AND subsection 匹配。
我已经使用了几个查询,这里是一个:
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到屏幕上也都是20s,但是另一列的值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());
}
【问题讨论】:
标签: android sqlite join database-cursor