我正在使用以下代码获取通知列表(总行数为 21):
List<Notification> list = new ArrayList<Notification>();
Cursor c = _db.query(TABLE_NAME, COL_ALL, null, null, null, null, order, get_limitStr(offset));
if(c != null && c.moveToFirst())
{
while(!c.isAfterLast())
{
Notification model = cursorToModel(c);
if(model != null)
{
list.add(model);
}
c.moveToNext();
}
c.close();
}
对于 offset = 0 生成的查询是
SELECT Id, Token, Title, Read, Message, Image, CreateDate, CreateDateFA FROM Notifications ORDER BY CreateDate DESC LIMIT 20,0
它按预期工作并返回 20 行,当我将偏移量增加 1(偏移量 = 1)时,它仅返回 1 行,这是正确的,但问题是当偏移量大于 1 时,查询将是
SELECT Id, Token, Title, Read, Message, Image, CreateDate, CreateDateFA FROM Notifications ORDER BY CreateDate DESC LIMIT 20,2
我认为它应该跳过 20 * 2 行然后开始从那里获取行,我的想法或我的查询是错误的。我在这里做错了什么?谢谢
最佳答案
LIMIT 20,2
and I thought it supposed to skip 20 * 2 rows and then starts taking rows from there, which either my thought or my query is wrong.
LIMIT 20,2
跳过前 20 行并最多返回剩余的 2 行。它与 LIMIT 2 OFFSET 20
相同。
即使是 documentation说这是违反直觉的:
Instead of a separate OFFSET clause, the LIMIT clause may specify two scalar expressions separated by a comma. In this case, the first expression is used as the OFFSET expression and the second as the LIMIT expression. This is counter-intuitive, as when using the OFFSET clause the second of the two expressions is the OFFSET and the first the LIMIT. This reversal of the offset and limit is intentional - it maximizes compatibility with other SQL database systems. However, to avoid confusion, programmers are strongly encouraged to use the form of the LIMIT clause that uses the "OFFSET" keyword and avoid using a LIMIT clause with a comma-separated offset.
如果您想实现页面大小为 20 的结果分页,请使用类似 OFFSET k*20 LIMIT 20
的内容,其中 k
是从零开始的页码.
关于java - 带偏移量的 android sqlite 查询不返回所需的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30458835/