使用SQLiteOpenHelper时进行JOIN查询的最佳方法是什么

时间:2012-10-16 11:51:26

标签: java android sqlite

我目前正在这样做。

有更好的方法吗?

public Cursor selectRostersForTeam(Activity activity, int teamId) {

    final String MY_QUERY = "SELECT r." + _ROSTER_ID + ", t." + _TEAM_ID + ", t." + TEAM_NAME + ", t." + TEAM_SEASON_WINS + ", t." + TEAM_SEASON_LOSSES + ", t." + TEAM_CHAMPIONSHIP_WINS + ", j." + _TEAMS_ROSTERS_ID + " FROM " + TABLE_TEAM + " AS p" + " JOIN " + TABLE_TEAMS_ROSTERS + " j ON (r." + _ROSTER_ID + " = j." + TEAMS_ROSTER_ROSTER_ID + ") " + " JOIN " + TABLE_TEAM + " ch ON (j." + TEAMS_ROSTER_TEAM_ID + " = t." + _TEAM_ID + ") WHERE j. " + TEAMS_ROSTER_TEAM_ID + " = " + teamId + ";";



    SQLiteDatabase db = getReadableDatabase();

    Cursor cursor = db.rawQuery(MY_QUERY, null);

    activity.startManagingCursor(cursor);

    return cursor;
}

1 个答案:

答案 0 :(得分:1)

rawQuery()的替代方案是query(),但该方法不是为加入而设计的。

如果您认为自己的加入非常重要,可以create a view将其加入,然后在query()的表格中使用它。


注意:建议将teamId之类的值作为参数传递,而不是将它们格式化为查询字符串:

rawQuery(..._TEAM_ID + " = ?", new String[] { Integer.toString(teamId) });