【问题标题】:SQLite Row_Num/IDSQLite Row_Num/ID
【发布时间】:2015-10-02 01:15:37
【问题描述】:

我有一个 SQLite 数据库,我正在尝试使用其中的数据,基本上有多个传感器写入数据库。我需要将一行连接到前一行来计算该时间段的价值差异。但唯一的问题是数据库中的 ROWID 字段不能再用于加入,因为有更多的传感器开始写入数据库。

在 SQL Server 中,使用 Row_Number 和按传感器分区会很容易。我找到了这个话题:How to use ROW_NUMBER in sqlite 并实施了建议:

select id, value , 
       (select count(*) from data b where a.id >= b.id and b.value='yes') as cnt 
from data a where  a.value='yes';

它可以工作,但速度很慢。有什么简单的我想念的吗?我试图加入可能的时差,创建一个视图。就在斗智斗勇!感谢您的任何想法!

这里是示例数据:

ROWID - SensorID - Time -     Value
1        2         1-1-2015     245
2        3         1-1-2015     4456
3        1         1-1-2015     52
4        2         2-1-2015     325
5        1         2-1-2015     76
6        3         2-1-2015     5154

我只需根据 sensorID 将第 6 行与第 2 行、第 3 行与第 5 行等连接起来。

【问题讨论】:

    标签: database sqlite


    【解决方案1】:

    可以使用index with the correct structure 加快子查询的速度。 在这种情况下,具有等式比较的列必须排在第一位,具有不等式的列排在第二位:

    CREATE INDEX xxx ON MyTable(SensorID, Time);
    

    【讨论】:

    • 谢谢!我创建了索引:CREATE INDEX xxx ON SensorResults (SensorID, ROWID); 并且正在使用这个查询,但它仍然很慢。有没有办法强制它使用索引? select rowid, sensord, time, value, (select count(*) from sensorresults b where a.rowid >=b.rowid and b.sensorid=2) as cnt from sensorresults a where a.sensorid=2
    • 好的,谢谢,它正在使用索引搜索初始查询,然后使用该索引搜索子查询。所以我不确定它会变得多好,无赖。
    猜你喜欢
    • 2016-03-03
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多