Efficient latest record query with Postgresql

前端 未结 5 947
深忆病人
深忆病人 2020-12-25 09:59

I need to do a big query, but I only want the latest records.

For a single entry I would probably do something like

SELECT * FROM table WHERE id = ?          


        
5条回答
  •  一个人的身影
    2020-12-25 10:16

    On method - create a small derivative table containing the most recent update / insertion times on table a - call this table a_latest. Table a_latest will need sufficient granularity to meet your specific query requirements. In your case it should be sufficient to use

    CREATE TABLE 
    a_latest 
    ( id INTEGER NOT NULL, 
      date TSTAMP NOT NULL, 
      PRIMARY KEY (id, max_time) );
    

    Then use a query similar to that suggested by najmeddine :

    SELECT a.* 
    FROM TABLE a, TABLE a_latest 
    USING ( id, date );
    

    The trick then is keeping a_latest up to date. Do this using a trigger on insertions and updates. A trigger written in plppgsql is fairly easy to write. I am happy to provide an example if you wish.

    The point here is that computation of the latest update time is taken care of during the updates themselves. This shifts more of the load away from the query.

提交回复
热议问题