Efficient latest record query with Postgresql

前端 未结 5 945
深忆病人
深忆病人 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:31

    this could be more eficient. Difference: query for table b is executed only 1 time, your correlated subquery is executed for every row:

    SELECT * 
    FROM table a 
    JOIN (SELECT ID, max(date) maxDate
            FROM table
          GROUP BY ID) b
    ON a.ID = b.ID AND a.date = b.maxDate
    WHERE ID IN $LIST 
    

提交回复
热议问题