我有3个表涉及: 门票,关系,时钟。
我需要从TICKETS表中获取ticket_id,将其连接到RELATIONS表以获取相关的incident_id(如果有的话),然后将incident_id加入CLOCKS表,并将所有“开放”时间加起来那个incident_id。
时钟表将为每个时钟名称多次列出incident_id(打开,正在进行中,已计划,待定客户,待定更改,待处理供应商,已解决),因此我必须按incident_id和sum进行分组(clock_time )。
这是我写的有效,但运行时间很长,即使是单张票:
Select
TBL1.Ticket_ID,
TBL1.Related_Incident,
TBL2.Total_Open_Clocks
From
(
Select
TICKETS.Ticket_ID,
RELATIONS.Related_incident
From
TICKETS left join RELATIONS ON
TICKETS.Ticket_ID = RELATIONS.Ticket_ID
WHERE
Ticket_ID = 'SDW123') as TBL1
Left Join
(
SELECT
Incident_Id,
SUM(clock_time) as Total_Open_Clocks
FROM
CLOCKS
Where clock_type In ('Open', 'Work In Progress', 'Pending Vendor')
Group by Incident_Id) as TBL2
on
TBL1.Related_Incident = TBL2.Incident_Id
如果我单独运行第一个查询,它将在大约1秒内运行。如果我单独运行第二个查询,它将在大约1秒内运行。单个票证的完整查询大约需要10分钟。
那么我可以做些什么来优化它以加快运行速度?我没有能力制作新表或临时表。
答案 0 :(得分:0)
您可以减少查询:
SELECT tk.Ticket_ID,
rl.Related_incident,
clk.Total_Open_Clocks
FROM TICKETS tk
LEFT JOIN RELATIONS rl
ON tk.Ticket_ID = rl.Ticket_ID
LEFT JOIN (SELECT Incident_Id,
SUM(clock_time) as Total_Open_Clocks
FROM CLOCKS
WHERE clock_type In ('Open', 'Work In Progress', 'Pending Vendor')
GROUP BY Incident_Id) clk
ON clk.Incident_Id = rl.Related_incident
WHERE Ticket_ID = 'SDW123'
到目前为止,我认为你有关于TICKETS(Ticked_ID)和RELATIONS(Related_incident)的索引。
尝试在CLOCKS上添加索引(Incident_id,clock_type)。
答案 1 :(得分:0)
可能是:
Select TICKETS.Ticket_ID, RELATIONS.Related_Incident,
sum(TBL2.clock_time) as Total_Open_Clocks
From TICKETS
left join RELATIONS ON TICKETS.Ticket_ID = RELATIONS.Ticket_ID
left join CLOCKS TBL2
ON TBL2.Incident_Id=RELATIONS.Related_Incident
and TBL2.clock_type In ('Open', 'Work In Progress', 'Pending Vendor')
WHERE TICKETS.Ticket_ID = 'SDW123'
Group by TICKETS.Ticket_ID, RELATIONS.Related_Incident
如果这给出了错误的结果,请显示表格和样本数据的结构。如果查询时间很长 - 显示explain plan