【问题标题】:Query for last record with identical values in a continuous block查询连续块中具有相同值的最后一条记录
【发布时间】:2015-01-31 04:13:44
【问题描述】:

在 SQLite 中,我有一个表格 datatable,格式如下:

+-----------------------+-----+-----+
|       timestamp       |  x  |  y  |
+-----------------------+-----+-----+
| "2015-01-30 23:00:00" |  1  |  1  |
| "2015-01-30 22:00:00" |  2  |  2  |
| "2015-01-30 21:00:00" |  2  |  2  |
| "2015-01-30 20:00:00" |  2  |  2  |
| "2015-01-30 19:00:00" |  3  |  3  |
| "2015-01-30 18:00:00" |  4  |  4  |
| "2015-01-30 17:00:00" |  2  |  2  |
+-----------------------+-----+-----+

我想在一个连续的块中提取最旧的记录(按时间戳),x,y 值与第二个最近条目的x,y 值匹配。我有一个有效的查询(见帖子结尾),但是对于多个子查询来说效率非常低。我知道一定有更好的方法。

使用我上面的示例表:

  1. 搜索坐标 x,y 必须与第二个最近条目中的 2,2 匹配(时间戳 = '2015-01-30 22:00:00')
  2. 记录必须来自相同x,y22:00-20:00)的连续块,但不能来自任何更早的也有坐标2,2(即17:00)的记录
  3. 预期值是此2,2 块或20:00 中最旧的记录

这是我目前的查询。它可以工作,但对于大型表可能会很慢 - 尤其是字符串连接。

-- find oldest time in continuous block that matches coordinates of interest
select min(timestamp) from datatable
where timestamp > (
    -- find most recent time that does not match coordinates of interest
    select max(timestamp) from datatable
    where timestamp < '2015-01-30 23:00:00'
    and x || ' | ' || y != (
        -- find coordinates of interest (2nd most recent record)
        select x || ' | ' || y
        from datatable
        where timestamp < '2015-01-30 23:00:00'
        order by timestamp
        limit 1
        -- returns 2 | 2
    )
    -- returns '2015-01-30 19:00:00
)
-- returns '2015-01-30 20:00:00 (which is the expected result)

【问题讨论】:

    标签: sql performance sqlite


    【解决方案1】:

    可以去掉串连:

    select min(timestamp), x, y
    from datatable
    where timestamp > (select max(timestamp)
                       from datatable
                       join (select x, y
                             from datatable
                             order by timestamp desc
                             limit 1 offset 1) as second
                       on datatable.x <> second.x
                       or datatable.y <> second.y
                       where timestamp < (select timestamp
                                          from datatable
                                          order by timestamp desc
                                          limit 1 offset 1))
    

    使用timestamp 上的索引,这两个查询都不会太糟糕。

    最快的方法可能是在应用程序中搜索块的末尾,即读取此查询的结果:

    select timestamp, x, y
    from datatable
    order by timestamp desc
    limit -1 offset 1
    

    并在x,y 值更改时停止。

    【讨论】:

      猜你喜欢
      • 2022-10-05
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      相关资源
      最近更新 更多