如何减少在postgres中运行查询的时间

时间:2019-10-18 09:09:23

标签: postgresql postgis query-performance postgresql-9.5

我有以下查询:

SELECT seq, node, edge, cost as cost, agg_cost, geom, sT_AsGeoJson(geom), replace(
    (REPLACE(sT_AsGeoJson(geom),
     ( select ST_AsGeoJson(geom1) from sample(20.983455,52.231909,20.973400,52.169647) a where seq1 in ( select  min(seq1) from sample(20.983455,52.231909,20.973400,52.169647 ))),
   (SELECT (St_asgeoJson(ST_LineSubstring((select (geom1) from sample(20.983455,52.231909,20.973400,52.169647) a where seq1 in (select  min(seq1) from sample(20.983455,52.231909,20.973400,52.169647 ))),(select ST_LineLocatePoint((select st_astext(geom1) from sample(20.983455,52.231909,20.973400,52.169647) a where seq1 in (select  min(seq1) from sample(20.983455,52.231909,20.973400,52.169647 ))), (ST_MakePoint(20.9850904,52.2318352)))),1)))
    ))),
     ( select ST_AsGeoJson(geom1) from sample(20.983455,52.231909,20.973400,52.169647) a where seq1 in ( select  max(seq1) from sample(20.983455,52.231909,20.973400,52.169647 ))),
    (SELECT st_asgeojson((ST_LineSubstring((select (geom1) from sample(20.983455,52.231909,20.973400,52.169647) a where seq1 in (select  max(seq1) from sample(20.983455,52.231909,20.973400,52.169647 ))),0,(select ST_LineLocatePoint
                ((select st_astext(geom1) from sample(20.983455,52.231909,20.973400,52.169647) a where seq1 in (select  max(seq1) from sample(20.983455,52.231909,20.973400,52.169647 ))), (ST_MakePoint(20.9741841,52.1691584)))))))
     ))
      FROM pgr_dijkstra 
    ('SELECT id, source, target, st_length(geom, true) as cost FROM roads',
      (SELECT source FROM roads ORDER BY ST_Distance( ST_StartPoint(geom), ST_SetSRID(ST_MakePoint(20.983455, 52.231909), 4326), true ) ASC LIMIT 1),
      (SELECT target FROM roads ORDER BY ST_Distance( ST_StartPoint(geom), ST_SetSRID(ST_MakePoint(20.973400, 52.169647), 4326), true ) ASC LIMIT 1)) as pt
     JOIN roads rd ON pt.edge = rd.id;

运行查询需要30秒。

有什么方法可以减少执行时间。

1 个答案:

答案 0 :(得分:0)

减少时间,您需要关心:

  1. 查询的复杂度,例如,如果您的子查询要转'N'次,那么整个查询将取O(N POW(M)),其中M是查询的记录总数,
  2. 简化复杂性之后,使用索引来加快查询的性能。
  3. 使用主键轻松识别表中的记录
  4. 尝试避免在子查询中使用'Limit'关键字
  5. 尝试避免在子查询中使用组功能

例如:在“ WHERE”子句中,您有“ pt.edge = rd.id” 您可以在“引用的

”表中创建两列edge和id的组合的索引