我在我的 SQLite 数据库中的两个表 table1 和 table2 上使用 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);
我在我的 SQLite 数据库中的两个表 table1 和 table2 上使用 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"));
..............
.............
}
编辑断开的链接:检查 rawQuery 方法在这里http://www.vogella.com/tutorials/AndroidSQLite/article.html 和这里http://www.codota.com/android/methods/android.database.sqlite.SQLiteDatabase/不同示例的rawQuery
Cursor c=databseobject.functionname() //where query is used
if(c.movetofirst()) {
do {
c.getString(columnindex);
} while(c.movetoNext());
}
您可以像访问任何其他查询一样访问结果。唯一的区别是有可能发生名称冲突,两个表上的列名相同。为了解决这些冲突,您需要使用表名作为前缀。
例如
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);
还有一个一般注意事项,最好不要使用“Select *...”,最好明确写出您要选择的列。
我使用以下内容进行内部连接:
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()方法检索所有列名。
希望这会给你一些提示。