我当前的查询使用roomId为我提供了某个房间的所有治疗对象。我只需要返回最后一个5.我可以使用db.query方法吗?或者我是否必须编写rawQuery SQL语句?
我应该只添加ORDER BY DESC并剪切我的列表数组吗?
哪个更好?
public List<Treatment> getLastFiveTreatmentsOfRoom(long roomId) {
// var to store last 5 treatments
List<Treatment> listTreatments = new ArrayList<Treatment>();
Cursor cursor = mDatabase.query(DatabaseOpenHelper.TABLE_TREATMENT, mAllColumns, DatabaseOpenHelper.KEY_TREATMENT_ROOM_ID
+ " =?", new String[] { String.valueOf(roomId) }, null, null, null);
if (cursor!= null) {
cursor.moveToFirst();
}
while (!cursor.isAfterLast()) {
Treatment treatment = cursorToTreatment(cursor);
listTreatments.add(treatment);
cursor.moveToNext();
}
// make sure to close cursor
cursor.close();
return listTreatments;
}
这些是我的领域 - &#34;添加&#34;是我需要排序的字段:它的TEXT NOT NULL
public static final String TABLE_TREATMENT = "treatment";
public static final String KEY_TREATMENT_ROWID = "_id";
public static final String KEY_TREATMENT_ISOLATION = KEY_ISO;
public static final String KEY_TREATMENT_TREATEDBY = "treated_by";
public static final String KEY_TREATMENT_ADDED = "added";
public static final String KEY_TREATMENT_HOSPITAL_ID = "hospitalId";
public static final String KEY_TREATMENT_ROOM_ID = "roomId";
这是填充添加字段的代码
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
String addedTime = currentTimestamp.toString();
答案 0 :(得分:1)
以下是查询方法签名:
query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
前一个参数是sql ORDER BY,而选择参数是sql WHERE。
所以你需要改变以下几行:
Cursor cursor = mDatabase.query(DatabaseOpenHelper.TABLE_TREATMENT, mAllColumns, DatabaseOpenHelper.KEY_TREATMENT_ROOM_ID
+ " =?", new String[] { String.valueOf(roomId) }, null, "YOUR_COLUMN DESC", null);