Proper way to access latest row for each individual identifier?

后端 未结 5 548
轻奢々
轻奢々 2021-01-03 11:14

I have a table core_message in Postgres, with millions of rows that looks like this (simplified):

┌────────────────┬──         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-03 11:47

    Another approach using ROW_NUMBER(), which is widely supported across RDBMS:

    SELECT * 
    FROM (
        SELECT 
            c.*,
            ROW_NUMBER() OVER(PARTITION BY mmsi ORDER BY time DESC) rn
        FROM core_message c
    ) AS cr WHERE rn = 1
    

    This query should benefit of existing index core_messag_mmsi_b36d69_idx.

提交回复
热议问题