我在SQLite数据库中的两个表表表1和表2上使用INNER JOIN。如何从游标访问结果(两个表的列)?这两个表有 2 个同名的列。
String query = SELECT * FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE name like '%c%';
Cursor c = newDB.rawQuery(query, null);
您可以指定列名而不是使用"*"。
String query = SELECT table1.id AS ID,table2.column2 AS c2,...... FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE name like '%c%';
然后使用列名 ID、c2 等进行访问。
while (cursor.moveToNext()) {
String c2 = cursor.getString(cursor.getColumnIndex("c2"));
int id = cursor.getInt(cursor.getColumnIndex("ID"));
..............
.............
}
编辑断开的链接:在此处检查原始查询 methid http://www.vogella.com/tutorials/AndroidSQLite/article.html这里 http://www.codota.com/android/methods/android.database.sqlite.SQLiteDatabase/rawQuery 不同的示例
您可以像访问任何其他查询一样访问结果。唯一的区别是有机会命名冲突,两个表上的列名相同。为了解决这些冲突,您需要使用表名作为前缀。
例如
Long id = c.getLong(c.getColumnIndex(tableName1 + "." + idColumnName));
如果这种方法不起作用。您应该按如下方式编写查询:
String query = SELECT table1.id AS table1_id FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE name like '%c%';
Cursor c = newDB.rawQuery(query, null);
还有一个一般说明,最好不要使用"选择 *..."最好明确写下要选择的列。
Cursor c=databseobject.functionname() //where query is used
if(c.movetofirst()) {
do {
c.getString(columnindex);
} while(c.movetoNext());
}
我使用了以下内容来执行内部连接:
public Cursor innerJoin(Long tablebId) {
String query = SELECT * FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE name like '%c%';
return database.rawQuery(query, null);
}
您可以按如下方式迭代光标:
Cursor cursor = innerJoin(tablebId); String result = ""; int index_CONTENT = cursor.getColumnIndex(KEY_CONTENT); cursor.moveToFirst(); do{ result = result + cursor.getString(index_CONTENT) + "n"; }while(cursor.moveToNext());
希望这对你有用
如果您知道列名,那么您可以像下面这样找到它,
long id = cursor.getLong(cursor.getColumnIndex("_id"));
String title = cursor.getString(cursor.getColumnIndex("title"));
如果您只想查看返回游标的所有列名,则可以使用 String[] getColumnNames() 方法来检索所有列名。
希望这能给你一些提示。