PostgreSQL时间戳 - 索引

Mor*_*kel 3 sql postgresql timestamp range

我正在运行一个查询,我在那里寻找一条记录,另一条记录在一段时间之后.

表定义:

(
  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
)
Run Code Online (Sandbox Code Playgroud)

在datetime,lokalitet,cowid,gpsstatus,gist-index on shape和shape_utm上有索引.

应该每隔5秒对这些点进行采样,所以我试着这样做

select <something more>,p1.timestamp 
from table p1, table p2 
where p1.timestamp + interval '5 secound' = p2.timestamp
Run Code Online (Sandbox Code Playgroud)

这样运行得相当快,但后来我发现由于采样中的抖动导致我丢失了很多点,所以这些点可能相隔4到6秒.

然后我尝试了:

where    (p2.timestamp, interval'0 second')
overlaps (p1.timestamp + interval '4 second', interval '2 second')
Run Code Online (Sandbox Code Playgroud)

这花了很多年.我也尝试过更简单的解决方案:

WHERE p1.timestamp + interval '4 second' <= p2.timestamp
AND   p1.timestamp + interval '6 second' >= p2.timestamp
Run Code Online (Sandbox Code Playgroud)

这最终也变得非常缓慢.

时间戳字段具有正常索引.是否有一种特殊的索引可以使这个查询可用?

目前的查询:

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;
Run Code Online (Sandbox Code Playgroud)

我也可以通过询问一些特定的时间间隔来获得可接受的查询时间.

Qua*_*noi 6

如果您只想要以前的记录,您可以:

SELECT  p, LAG(p) OVER (ORDER BY timestamp) AS pp
FROM    table p
ORDER BY
        timestamp
Run Code Online (Sandbox Code Playgroud)

如果你需要一个记录46之前,在当前秒,使用:

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
Run Code Online (Sandbox Code Playgroud)

如果它们都在范围内,则可以返回多个先前的记录.