我必须从表中获得最后两个元素(或者只是id)。我的元素的id增加但不增加(下一个值总是更大,但有可能超过1 - 元素是由其他人创建的,我不应该修改它们。)
我知道如何识别最后一个:
public Long getLastDay(){
Cursor cursor= mDatabase.query(DatabaseHelper.TABLE_DAYS, new String[]{"MAX(" + DatabaseHelper.COLUMN_DAY_ID + ")"}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
return (cursor.getLong(0));
}
return Long.parseLong("0");
}
例如ids:
1 4 7 11 14 15 19 25 28
我希望得到28
(有效)和25
。
如何获得第二个值?
@EDIT:
我的代码是:
public Long getSecondLastDay(){
Cursor cursor= mDatabase.rawQuery("SELECT "+DatabaseHelper.COLUMN_DAY_ID+" FROM " + DatabaseHelper.TABLE_DAYS+ " LIMIT 2", null);
if (cursor != null) {
cursor.moveToFirst();
return (cursor.getLong(0));
}
return Long.parseLong("0");
}
答案 0 :(得分:0)
使用cursor.moveToLast然后使用cursor.moveToPreviuous
答案 1 :(得分:0)
按相反方向排序天数,然后只取前两行:
Cursor cursor = mDatabase.query(DatabaseHelper.TABLE_DAYS,
new String[]{ DatabaseHelper.COLUMN_DAY_ID },
null, null, null, null,
DatabaseHelper.COLUMN_DAY_ID + " DESC",
"2");
long secondToLastDay = 0, lastDay = 0;
if (cursor.moveToFirst()) {
lastDay = cursor.getLong(0);
if (cursor.moveToNext())
secondToLastDay = cursor.getLong(0);
}