SQLite查询间隔中的一系列条目

时间:2016-05-25 15:49:30

标签: android sqlite pagination android-sqlite

我想实现一个SQL-Query,它为我提供了一系列条目。例如:

public List<Entry> getEntries(int lowerValue, int upperValue){
//Select upper - lower entries.
}

getEntries(0, 20) --> First 20 Entries
getEntries(21, 40) --> Entry 21 to 40
getEntries(12, 200) --> Entry 12 to 200

目前,我得到了这样的所有条目:

public List<Log> getLogs(){
        List<Log> list = new ArrayList<>();
        SQLiteDatabase db = getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_LOGS + " WHERE 1";

        //Cursor points to a location in your results
        Cursor c = db.rawQuery(query, null);
        //Move to the first row in your results
        c.moveToFirst();

        //Position after the last row means the end of the results
        while (!c.isAfterLast()) {
            if (c.getString(c.getColumnIndex("type")) != null) {
                int id = c.getInt(c.getColumnIndex("_id"));
                int type = c.getInt(c.getColumnIndex("type"));
                long date = c.getLong(c.getColumnIndex("date"));
                int refId = c.getInt(c.getColumnIndex("refId"));
                String extra = c.getString(c.getColumnIndex("extra"));

                list.add(new Log(id, type, date, refId, extra));
            }
            c.moveToNext();
        }
        db.close();
        c.close();
        return list;
    }

我知道有一个LIMIT子句,但始终从第一个条目开始。

1 个答案:

答案 0 :(得分:0)

您需要的是LIMIT和OFFSET的组合

您可以使用

LIMIT <skip>, <count>

LIMIT <count> OFFSET <skip>

所以一些例子是

"SELECT * FROM " + TABLE_LOGS + " WHERE type=1 LIMIT 20 OFFSET 0"
"SELECT * FROM " + TABLE_LOGS + " WHERE type=1 LIMIT 20 OFFSET 20"
"SELECT * FROM " + TABLE_LOGS + " WHERE type=1 LIMIT 20 OFFSET 40"

希望这有帮助。