MySQL查詢優化技巧之二
1. 多表聚合查詢優化
在實際的業務場景中經常會需要多表關聯,需要使用到多個表的欄位關聯聚合結果,對於新手來說,最直觀的想法就是把所有資料來源join成一張大表,再在大表中進行指標的計算,但是這樣子就會效率非常低下
最好的方法就是:
先把多張表的資料進行欄位聚合,再在聚合過後的基礎上進行表關聯
例如:
表A: adv_id, date, ad_id, material_id,ad_name, self_imp, self_click
表B:adv_id, date,ad_id,material_id,ad_name,target_imp_taget_click
表C; adv_id, date,ad_id,material_id,ad_name,third_imp,third_click
需要的查詢結果;adv_id,self_imp, self_click, target_imp_taget_click, third_imp,third_click
最好的查詢方案:
select t1.*, t2.targt_imp,t2.target_click,t3.third_imp,t3.third_click
from
(select adv_id,, sum(self_imp)as self_imp,sum(self_click) as self_click from table_A group by adv_id) t1
left join
(select adv_id, sum(target_imp) astarget_imp, sum(target_click) as target_click from table B group by adv_id) t2
on t1.adv_id=t2.adv_id
left join
(select adv_id, sum(third_imp) as third_imp,sum(third_click) as third_click from table C group by adv_id) t3
on t1.adv_id=t3.adv_id