我正在运行一个查询,我在其中查找一条记录,并在一段时间后查找另一条记录。
表定义:
(
id integer primary key,
gpsstatus character(2),
datetime timestamp without time zone,
lat numeric(9,6),
lon numeric(9,6),
alt numeric(9,4),
time integer,
datafileid integer,
shape geometry,
speed double precision,
dist double precision,
shape_utm geometry,
lokalitet character(128),
cowid integer
)
在datetime、lokalitet、cowid、gpsstatus 上有索引,在shape 和shape_utm 上有gist-index。
这些点应该每 5 秒采样一次,所以我尝试这样做
select <something more>,p1.timestamp
from table p1, table p2
where p1.timestamp + interval '5 secound' = p2.timestamp
这运行得相当快,但后来我发现由于采样中的抖动,我丢失了很多点,因此这些点可能相隔 4 到 6 秒。
然后我尝试了:
where (p2.timestamp, interval'0 second')
overlaps (p1.timestamp + interval '4 second', interval '2 second')
这花了很长时间。我还尝试了更简单的解决方案:
WHERE p1.timestamp + interval '4 second' <= p2.timestamp
AND p1.timestamp + interval '6 second' >= p2.timestamp
这也最终变得非常慢。
时间戳字段有一个正常的索引。是否有一种特殊的索引或其他东西可以使这个查询可用?
此时的查询:
SELECT
p1.cowid,
p1.datetime,
st_distance(p1.shape_utm, lead(p1.shape_utm)
OVER (ORDER BY p1.datetime)) AS meters_obs,
st_distance(p1.shape_utm, lead(p1.shape_utm, 720)
OVER (ORDER BY p1.datetime)) AS meters_hour,
observation.observation
FROM (gpspoint p1 LEFT JOIN observation
ON (observation.gpspointid = p1.id)),
status
WHERE p1.gpsstatus = status.id
AND status.use = true;
我也可以通过询问一些特定的时间间隔来获得可接受的查询时间。
最佳答案
如果你只想要以前的记录,你可以这样做:
SELECT p, LAG(p) OVER (ORDER BY timestamp) AS pp
FROM table p
ORDER BY
timestamp
如果你需要在当前之前记录 4
到 6
秒,使用这个:
SELECT p1.*, p2.*
FROM table p1
LEFT JOIN
table p2
ON p2.timestamp BETWEEN p1.timestamp - '4 seconds'::INTERVAL
AND p1.timestamp - '6 seconds'::INTERVAL
ORDER BY
p1.timestamp
如果它们都在范围内,这可能会返回多个以前的记录。
关于sql - PostgreSQL 时间戳 - 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607759/