我正在尝试搜索数据库,并在同一个表中找到插入特定事项的两条记录。这将告诉我必须在系统中进行一些优化。
我尝试了很多查询,最终给了我正确的结果:
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
记录相匹配。
在示例一中,查询很简单:
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)查询吗?
答案 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的索引将改善性能。