需要Postgres查询改进

时间:2015-12-11 17:33:02

标签: sql performance postgresql

我必须改进此查询:

SELECT pt.equip, pt.date, pt.cod,  
(  
SELECT pt2.date  
FROM "TABLE" pt2  
WHERE 1=1  
AND pt2.equip = pt.equip  
AND CAST(pt2.date AS DATE) between '2015/12/01' AND '2015/12/02'  
AND pt2.cod in (17, 84, 85)  
AND pt2.date > pt.date  
ORDER BY pt2.date  
LIMIT 1  
)  
FROM "TABLE" pt   
WHERE pt.cod is not null  
AND pt.equip IN (2,3,8,7)  
AND CAST(pt.date AS DATE) between '2015/12/01' AND '2015/12/02'  
AND pt.cod in (16, 81, 82)  

子查询与主查询的表相同 cod 列定义第一个查询中的初始句点, cod 定义第二个查询的结尾。
如何使用装备 dateInitial (第一个查询), dateEnd (第二个查询)<?p>列进行查询

1 个答案:

答案 0 :(得分:2)

此查询的一种方法是在表之间执行LEFT JOIN,然后使用DISTINCT ON

SELECT DISTINCT ON (pt.equip, pt.date, pt.cod) pt.*, pt2.*
FROM "TABLE" pt LEFT JOIN
     "TABLE" pt2
     ON pt2.equip = pt.equip AND
        CAST(pt2.date AS DATE) between '2015/12/01' AND '2015/12/02' AND
        pt2.cod in (17, 84, 85) AND
        pt2.date > pt.date
WHERE pt.cod is not null AND
      pt.equip IN (2,3,8,7) AND
      CAST(pt.date AS DATE) between '2015/12/01' AND '2015/12/02' AND
      pt.cod in (16, 81, 82)  
ORDER BY pt.equip, pt.date, pt.cod, pt2.date DESC;

从版本9.3开始,Postgres还支持横向连接,它允许子查询位于FROM子句中,从而可以更容易地从结果集中选择多个列。