PostgreSQL return exact or closest date to queried date

前端 未结 2 996
小蘑菇
小蘑菇 2021-02-05 11:55

I have the following postgresql syntax that returns values WHERE session_date matches $date_string

Problem is that sometimes the $date_string will not be available in th

2条回答
  •  野的像风
    2021-02-05 12:22

    Using btree_gist and knn

    Using this method you can find the nearest event with an index.

    CREATE EXTENSION btree_gist;
    CREATE TABLE foo ( id serial, ts timestamp );
    
    INSERT INTO foo (ts)
    VALUES
      ('2017-06-02 03:09'),
      ('2016-06-02 03:09'),
      ('1900-06-02 03:09'),
      ('1954-06-02 03:09');
    
    CREATE INDEX ON foo USING gist(ts);
    
    SELECT *
    FROM foo
    ORDER BY '1950-06-02 03:09' <-> ts
    LIMIT 1;
    

    Pg 11

    Coming some time in the distant future... with knn/btree

提交回复
热议问题