我想优化以下查询。对于少量记录,它花费超过2分钟。是否可以删除UNION并优化查询
Select cia.cia_orderamount, cia.cia_notes, cia.cia_mincount, cia.cia_customerid, cia.cia_id, cia.cia_locationid, lc.locationcode, T1.instock, c.id as customerid, c.customer
From cardinventoryalerts cia
Inner join customers c on cia.cia_customerid = c.id and c.useautocardorder = 1
Inner Join locationcodes lc on cia.cia_locationid = lc.id
left JOIN
(SELECT cb.customer, Case when cb.locationcode is null or cb.locationcode = '' Then NULL Else cb.locationcode End as locationcode,
sum( CASE WHEN cb.issued = 'no' THEN 1 ELSE 0 END) as instock
FROM cardbatch cb
Group By cb.customer, cb.locationcode
) as T1 on lc.locationcode = T1.locationcode and T1.customer = c.customer
WHERE (cia_mincount > T1.instock or T1.instock is NULL)
UNION
Select cia.cia_orderamount, cia.cia_notes, cia.cia_mincount, cia.cia_customerid, cia.cia_id, -1, NULL, T1.instock, c.id as customerid, c.customer
From cardinventoryalerts cia
Inner join customers c on cia.cia_customerid = c.id and c.useautocardorder = 1
left JOIN
(SELECT cb.customer, -1, sum( CASE WHEN cb.issued = 'no' THEN 1 ELSE 0 END) as instock
FROM cardbatch cb
where cb.locationcode is null or cb.locationcode = ''
Group By cb.customer
) as T1 on c.customer = T1.customer
WHERE (cia_mincount > T1.instock or T1.instock is NULL) and cia.cia_locationid is null
解释此查询:
UNION RESULT <union1,3> ALL
1 PRIMARY c ALL PRIMARY,id 2 Using where
1 PRIMARY cia ALL fk_ciacustid,fk_cialocationid 3 Using where
1 PRIMARY lc eq_ref PRIMARY,id PRIMARY ... quiz.cia.cia_locationid 1
1 PRIMARY <derived2> ALL 3 Using where
2 DERIVED cb index customer_loc ... 3
3 UNION cia ref fk_ciacustid,fk_cialocationid fk_cialocationid ... const 1 Using where
3 UNION c eq_ref PRIMARY,id PRIMARY ... quiz.cia.cia_customerid 1 Using where
3 UNION <derived4> ALL 1 Using where
4 DERIVED cb index customer_loc ... 3 Using where
答案 0 :(得分:0)
我认为您可以将两个FROM部分组合在一起(见下文),将内部加入位置代码替换为左连接位置代码并正确编写WHERE条件
From cardinventoryalerts cia
Inner join customers c on cia.cia_customerid = c.id and c.useautocardorder = 1
left Join locationcodes lc on cia.cia_locationid = lc.id
left JOIN
(SELECT cb.customer, Case when cb.locationcode is null or cb.locationcode = '' Then NULL Else cb.locationcode End as locationcode,
sum( CASE WHEN cb.issued = 'no' THEN 1 ELSE 0 END) as instock
FROM cardbatch cb
Group By cb.customer, cb.locationcode
) as T1 on lc.locationcode = T1.locationcode and T1.customer = c.customer
left JOIN
(SELECT cb.customer, -1, sum( CASE WHEN cb.issued = 'no' THEN 1 ELSE 0 END) as instock
FROM cardbatch cb
where cb.locationcode is null or cb.locationcode = ''
Group By cb.customer
) as T1 on c.customer = T1.customer