试图在Postgres sql中优化子查询

时间:2016-11-23 17:32:40

标签: sql postgresql

我已经在这个问题上工作了一段时间,我终于得到它来产生我想要的结果。但是,运行需要很长时间。我希望有一些优化技巧可以让它运行得更快一点?

LEFT OUTER JOIN
                 (
SELECT testschedule."asset_id" as asset_id, 
testschedule."test_id" as    test_id,
testresult."id" as testresult_id, 
testschedule."testtaken", 
testresult."testdate" as testdate,
testschedule."testdate" as scheduledate, 
verify."testresult_id" as scheduleresult_id, 
testschedule."testresult_id" as rankidtest,

ROW_NUMBER() OVER (PARTITION BY 
testschedule."asset_id",  testschedule."test_id", 
testschedule."testdate" 

ORDER BY testresult."testdate" ASC) as ranking

FROM
                    "public"."testresult" testresult 
LEFT OUTER JOIN "public"."testschedule" testschedule 
ON
testschedule."asset_id" = testresult."asset_id" 
and testschedule."test_id" = testresult."test_id"

   LEFT OUTER JOIN
               (SELECT testschedule."testresult_id",  
      testschedule."asset_id" 
      as asset_id, 
      testschedule."test_id" as test_id from
      "public"."testschedule" testschedule

    where 
      testschedule."client_id" = 25368272
      and testschedule."testdate" > '2016-06-01' 
      and testschedule."testdate" < '2016-10-20' ) verify 
    ON verify."testresult_id" = testresult."id" 
      and verify."test_id" = testschedule."test_id" and
      verify."asset_id" = testschedule."asset_id"

 WHERE

     testschedule."client_id" = 25368272

     and testresult."testdate" > 
     testschedule."maxtolerancedate" 
     and testresult."testdate" > '2016-06-01'
     and testschedule."testdate" > '2016-06-01' 
     and testschedule."testdate" < '2016-10-20'
   ) rank
 ON rank.asset_id = asset."id"
   and rank.test_id = test."id"
   and testschedule."testdate" = rank.scheduledate
   and rank.ranking = 1

目前,对于20900多行(每个客户端有所不同),此约为39秒。那显然我想要的时间长一点。 &#34; rank&#34;中的子查询带别名的子查询&#34;验证&#34;是否链接正确的testchedule。&#34; testresult_id&#34;与testresult的第1行编号一起使用。&#34; testdate&#34;。是否有一个我遗漏的明显修复?

0 个答案:

没有答案