高效的SQL来检索热门结果

时间:2017-03-12 10:46:37

标签: sql postgresql

我有下表:

id, first_name, last_name, score, feedback, report_date
1,  Barry     , Smith    , 5    , positive, 2017-02-01
2,  John      , Smith    , 6    , negative, 2017-02-01
3,  Barry     , Smith    , 3    , negative, 2017-01-31
5,  John      , Smith    , 1    , positive, 2017-01-31

我想检索姓名的最新得分和反馈。

我尝试了以下查询:

select m.ad_id, m.country, m.score, m.feedback
from records m
inner join  (
   select first_name, last_name, max(report_date) as max_date
   from records
   where report_date <= '2017-02-19 15:00:00'
     and report_date >='2017-02-19 10:00:00'
     and score is not null
   GROUP BY first_name, last_name
   ) mp  on m.first_name = mp.first_name
         and m.last_name=mp.last_name
         and m.report_date = mp.max_date
         and m.report_date <= '2017-02-19 15:00:00'
         and m.report_date>='2017-02-19 10:00:00'
   ;

然而,在18M的记录中,它需要几秒钟。

进行简单的查询:

select m.fist_name, m.last_name, m.score, m.feedback
from records m
where m.report_date <= '2017-02-19 15:00:00'
  and m.report_date>='2017-02-19 10:00:00' 
  and score is not null

不到半秒,然而它将返回x量的记录,这需要更多的流量。 如何使第一个查询更有效?

1 个答案:

答案 0 :(得分:2)

distinct on

select distinct on (first_name, last_name) *
from records
where
    report_date <= '2017-02-19 15:00:00' and report_date >='2017-02-19 10:00:00' 
    and score is not null
order by first_name, last_name, report_date desc