优化同一个表的两个记录之间的连接

时间:2017-06-15 14:36:49

标签: postgresql

我正在尝试搜索数据库,并在同一个表中找到插入特定事项的两条记录。这将告诉我必须在系统中进行一些优化。

我尝试了很多查询,最终给了我正确的结果:

SELECT woh.*
FROM workorderhistory woh 
WHERE woh.operation = 'REQ_CONVER' AND woh.operationtime > (
    SELECT MAX(woh2.operationtime) FROM workorderhistory woh2 WHERE woh2.operation = 'CLOSE' 
) AND woh.workorderid = woh2.workorderid
ORDER BY woh.workorderid DESC
LIMIT 100

然而,这一个花了1.5小时,在16000个记录中...... 所以这绝对不适合我...

查询中最大的问题是我只需要将我的条件与最新的closed记录相匹配。

数据将解释更多: Two data tables

在示例一中,查询很简单:

SELECT woh.*
FROM workorderhistory woh 
INNER JOIN workorderhistory woh2
ON woh.workorderid = woh2.workorderid
WHERE woh.operation = 'REQ_CONVER' AND woh2.operation = 'CLOSE' AND woh.operationtime > woh2.operationtime

但是,我需要先检索最后关闭的记录。这是我需要的比较记录。

我尝试使用带有子查询的INNER JOIN执行此操作:

SELECT woh.*, woh2.operationtime AS woh2operationtime, woh2.operationtime AS woh2operationtime
FROM workorderhistory woh 
INNER JOIN (SELECT workorderid, operationtime FROM workorderhistory WHERE operation = 'CLOSE' ORDER BY historyid DESC LIMIT 1) woh2
ON woh.workorderid = woh2.workorderid AND woh2.operationtime < woh.operationtime
WHERE woh.operation = 'REQ_CONVER'
ORDER BY woh.workorderid ASC
LIMIT 100

但它没有返回正确的结果,它仍然使用了第一个CLOSE记录。

知道如何为PostgresSQL优化这个(imo super-simple)查询吗?

2 个答案:

答案 0 :(得分:1)

请试试这个

Drop table if exists TMP_ workorderhistory;
Create temp table TMP_ workorderhistory as
SELECT 
    Workorderid
  , operationtime 
From (
       SELECT 
          Workorderid
        , operationtime 
        , row_number() over(partition by Workorderid order by historyid desc) AS RNO
       FROM workorderhistory 
       WHERE operation = 'CLOSE' 
     ) A
Where A.RNO = 1;

SELECT woh.*
FROM workorderhistory woh 
INNER JOIN TMP_ workorderhistory woh2
ON woh.workorderid = woh2.workorderid
WHERE woh.operation = 'REQ_CONVER' AND woh.operationtime > woh2.operationtime;

答案 1 :(得分:1)

希望我理解你的问题。

{{1}}

列workorderid的索引将改善性能。