【问题标题】:SQLite Query a range of entries in intervalSQLite 查询区间内的一系列条目
【发布时间】:2016-09-23 08:24:57
【问题描述】:

我想实现一个 SQL 查询,它可以提供一系列条目。示例:

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 子句,但它总是从第一个条目开始。

【问题讨论】:

    标签: android sqlite pagination android-sqlite


    【解决方案1】:

    你需要的是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"
    

    希望这会有所帮助。

    【讨论】:

    • 这很好用。你也可以帮忙吗?`当我尝试订购我的条目时出现此错误:android.database.sqlite.SQLiteException: near "WHERE": syntax error (code 1): , while compile: SELECT * FROM logs ORDER BY _id DESC WHERE 1 LIMIT 3 OFFSET 0
    • 是的。我应该在回答之前发现这一点,但是您需要设置 WHERE 来比较列。所以像WHERE type=1.
    • 没有以前已经工作过的。但是当我尝试按 ID 订购时,我收到了这个错误!
    • 尝试将ORDER BY _id DESC 放在语句的末尾。如果有记忆,这是一个要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多