Optimize GROUP BY query to retrieve latest row per user

后端 未结 3 1870
南笙
南笙 2020-11-21 11:12

I have the following log table for user messages (simplified form) in Postgres 9.2:

CREATE TABLE log (
    log_date DATE,
    user_id  INTEGER,
    payload           


        
3条回答
  •  既然无缘
    2020-11-21 11:51

    Perhaps a different index on the table would help. Try this one: log(user_id, log_date). I am not positive that Postgres will make optimal use with distinct on.

    So, I would stick with that index and try this version:

    select *
    from log l
    where not exists (select 1
                      from log l2
                      where l2.user_id = l.user_id and
                            l2.log_date <= :mydate and
                            l2.log_date > l.log_date
                     );
    

    This should replace the sorting/grouping with index look ups. It might be faster.

提交回复
热议问题