sqlite - 为给定数据定位正确 OFFSET 的最佳方法

标签 sqlite

为了避免一次获取所有数据,这会导致内存不足,我们在我们的应用程序中使用 limitoffset 实现分页。

每次,我们的应用程序只会显示 1 个页面。

Page 0 : select * from note order by order_id limit 10000 offset 0;
Page 1 : select * from note order by order_id limit 10000 offset 10000;
Page 2 : select * from note order by order_id limit 10000 offset 20000;
Page 3 : select * from note order by order_id limit 10000 offset 30000;
...

每当用户添加新数据时,我们就知道从 SQLite 中查找数据的搜索条件。

select * from note where uuid = '1234-5678-9ABC';

但是,我们需要使用正确的页面重新加载我们的应用。

但是,我们不知道如何才能有好的速度性能,找出新数据属于哪个页面(哪个偏移量)。

我们可以通过下面的暴力方式来找出数据属于哪个偏移量

select * from (select * from note order by order_id limit 10000 offset 0) where uuid = '1234-5678-9ABC';

select * from (select * from note order by order_id limit 10000 offset 10000) where uuid = '1234-5678-9ABC';

select * from (select * from note order by order_id limit 10000 offset 20000) where uuid = '1234-5678-9ABC';

select * from (select * from note order by order_id limit 10000 offset 30000) where uuid = '1234-5678-9ABC';

...

但是,这是非常低效的。

有没有什么“聪明”的方法,可以让我们有很好的速度性能,为给定的数据定位正确的偏移量?

谢谢。

最佳答案

使用 row_number() 查找偏移量

可以使用row_number 窗口函数计算行索引来计算偏移量。 https://www.sqlite.org/windowfunctions.html#builtins

查找行索引

select
    uuid, (row_number() over (order by order_id) - 1) as row_index
from note

查找偏移量

可以使用模块化算法计算偏移量。

select row_index - (row_index % 10000) as offset
from note_row_index
where uuid = '1234-5678-9ABC'

在查询中使用偏移量

with note_row_index(uuid, row_index) AS (
    select
        uuid, (row_number() over (order by order_id) - 1) as row_index
    from note
),
note_offset(offset) AS (
    select row_index - (row_index % 10000) as offset
    from note_row_index
    where uuid = '1234-5678-9ABC'
)
select *
from note
order by order_id
limit 10000
offset (select offset from note_offset)

关于sqlite - 为给定数据定位正确 OFFSET 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73476334/

相关文章:

python - 关于 Pandas DF 的另一个 SQL 问题。帮我一劳永逸地结束这些

python - SQLite3 查询 ORDER BY 参数与?符号

SQLITE:1次提交后查找多个表的状态

java - 未创建 SQLite 数据库文件

ruby-on-rails - Sqlite where 子句不起作用(这是一个错误吗?)

sqlite - Cordova /Phonegap ORM?

c++ - windows下使用sqlite

iphone - 核心数据存储(sqlite)备份的最佳实践?

android - 如何在查询 sqlite 时格式化 DateTime 列?

unit-testing - 使用 SQLite "No Such Table"测试 NHibernate - 生成了模式