【发布时间】: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 值匹配。我有一个有效的查询(见帖子结尾),但是对于多个子查询来说效率非常低。我知道一定有更好的方法。
使用我上面的示例表:
- 搜索坐标
x,y必须与第二个最近条目中的2,2匹配(时间戳 = '2015-01-30 22:00:00') - 记录必须来自相同
x,y(22:00-20:00)的连续块,但不能来自任何更早的也有坐标2,2(即17:00)的记录 - 预期值是此
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