Optimize groupwise maximum query

前端 未结 4 739
温柔的废话
温柔的废话 2020-11-30 14:21
select * 
from records 
where id in ( select max(id) from records group by option_id )

This query works fine even on millions of rows. However as y

4条回答
  •  悲哀的现实
    2020-11-30 14:41

    select distinct on (option_id) *
    from records
    order by option_id, id desc
    

    Indexes will only be used if the cardinality is favorable. That said you can try a composite index

    create index index_name on records(option_id, id desc)
    

提交回复
热议问题