Optimizing ORDER BY

前端 未结 5 1683
野趣味
野趣味 2021-01-21 08:21

I am trying to optimize this query that sorts posts by reputation field (1st) and then id field (2nd). Without 1st field query takes ~0.25

5条回答
  •  情书的邮戳
    2021-01-21 08:33

    select * 
    from (
      SELECT -- everything is ok here
      , CASE 
          WHEN p.created_at >= unix_timestamp(now() - INTERVAL p.reputation DAY) 
            THEN + p.reputation ELSE NULL END order_col
      FROM posts AS p
      WHERE p.status = 'published' -- the only thing for filter
      LIMIT 0,10 -- limit provided as well
    ) a
    ORDER BY 
        a.order_col desc
        ,a.id DESC
    

提交回复
热议问题