我正在使用 sqlite、LocationsContentProvider 开发 Android 应用程序。 我在 JOIN 方面遇到了一些问题。
这工作正常:
// Returns all the locations from the table
public Cursor getAllLocations(){
Cursor cursor;
cursor = mDB.query(DATABASE_TABLE, new String[] { FIELD_ROW_ID, FIELD_LAT , FIELD_LNG, FIELD_ZOOM, FIELD_ADDRESS } , null, null, null, null, null);
Log.d(TAG, "DB: query complete" + cursor );
return cursor;
}
这不起作用:
// Return all locations joined with sub map name
public Cursor getAllLocations(){
Cursor cursor;
String query;
query = "SELECT a._id, a.lat, a.lng, a.sub_map_id, a.zoom, a.address, b._id, b.sub_map FROM locations a" +
" INNER JOIN sub_map_table b ON a.sub_map_id=b._id";
Log.d(TAG, "DB: query = \n" + query;
Log.d(TAG, "DB: query complete" );
cursor = mDB.rawQuery(query, null);
return cursor;
}
有关数据库结构的其他一些详细信息:
// Fields for locations table
public static final String FIELD_ROW_ID ="_id";
public static final String FIELD_LAT = "lat";
public static final String FIELD_LNG = "lng";
public static final String FIELD_ZOOM = "zoom";
public static final String FIELD_ADDRESS ="address";
public static final String FIELD_SUB_MAP_ID = "sub_map_id";
// Fields for SUB_MAP_TABLE table
public static final String FIELD_SUB_MAP_ROW_ID = "_id";
public static final String FIELD_SUB_MAP = "sub_map";
//table name, a constant
private static final String DATABASE_TABLE = "locations";
private static final String SUB_MAP_TABLE = "sub_map_table";
private static final String TAG = null;
//instance variable for SQLiteDatabse
private SQLiteDatabase mDB;
//constructor
public LocationsDB(Context context) {
super(context, DBNAME, null, VERSION);
this.mDB = getWritableDatabase();
}
/** This is a callback method, invoked when the method getReadableDatabase() / getWritableDatabase() is called
* provided the database does not exists
* */
@Override
public void onCreate(SQLiteDatabase db) {
String create_table_locations = "create table " + DATABASE_TABLE + " ( " +
FIELD_ROW_ID + " integer primary key autoincrement , " +
FIELD_LNG + " double , " +
FIELD_LAT + " double , " +
FIELD_ZOOM + " text , " +
FIELD_ADDRESS + " text , " +
FIELD_SUB_MAP_ID + " integer " +
" ) ";
String create_table_submap = "create table " + SUB_MAP_TABLE + " ( " +
FIELD_SUB_MAP_ROW_ID + " integer primary key autoincrement , " +
FIELD_SUB_MAP + " text " +
" ) ";
db.execSQL(create_table_locations);
db.execSQL(create_table_submap);
我一整天都在看这个,但我不知道出了什么问题。请建议我。 好像什么都没有传送过来?或者,即使它已发送,也不会被捕获。
最佳答案
通过“似乎没有发送任何内容”,我认为您没有遇到错误,只是您的查询没有返回任何数据?
如果是这种情况,则问题可能出在您的数据上。 “location”中 sub_map_id 为 NULL 的任何行都将导致连接失败并且不会被返回。同样,任何 sub_map_id 在 sub_map_table 中没有 _id 匹配条目的行都不会被返回。
如果您使用 LEFT JOIN 而不是 INNER JOIN,那么您将获得“location”中的所有行。但是,如果连接到 sub_map_table 失败,则 b._id 和 b.sub_map 返回的值将为 NULL。
此外,结果集中有重复的列名,即 a._id 和 b._id 都将返回列名“_id”,如果您尝试从游标引用它们,这将导致问题。您可以使用 AS 来区分它们,并在结果中为它们指定唯一的名称,例如:
SELECT a._id AS a_id, b._id AS b_id
关于Android sqlite JOIN不显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19155420/