2011-11-23 118 views
3

快2-3倍這個查詢單獨運行:選擇查詢比視圖

SELECT 
    -- lots of columns 
FROM 
    table1 t1 
    LEFT JOIN table2 t2 
     ON t2.[userid] = t1.[userid] 
    LEFT JOIN table3 t3 
     ON t1.[orderid] = t3.[orderid] 
    LEFT JOIN table4 t4 
     ON t4.[orderitemlicenseid] = t3.[orderitemlicenseid] 
    LEFT JOIN table5 t5 
     ON t1.[orderid] = t5.[orderid] 
    LEFT JOIN table6 t6 
     ON t5.[transactionid] = t6.[transactionid] 
    LEFT JOIN table7 t7 
     ON t7.[transactionid] = t5.[transactionid] 
    LEFT JOIN table8 t8 
     ON t8.[voucherid] = t7.[voucherid] 
    LEFT JOIN table9 t9 
     ON t8.[voucherid] = t9.[voucherid] 
    LEFT JOIN table10 t10 
     ON t10.[vouchergroupid] = t9.[vouchergroupid] 
     AND t10.[territoryid] = t2.[territoryid] 
    LEFT JOIN table11 t11 
     ON t11.[voucherid] = t8.[voucherid] 
    LEFT JOIN table12 t12 
     ON t12.[orderid] = t1.[orderid] 
GROUP BY 
    t5.[transactionid] 

大約需要2.5秒完成。當我將它保存爲視圖並將其運行爲:

SELECT * FROM viewName;

完成需要7秒。

什麼原因,我怎樣才能使視圖更快?

+0

爲什麼你反覆打開並雙擊括號? – Matthew

+0

您是否在視圖中添加了任何「WHERE」條件? – Matthew

+0

@Matthew PK這不是我,我在這裏發佈SQL之前就使用了SQL格式化工具。實際的SQL中沒有括號。 –

回答

6

在MySql中處理視圖的方式存在性能問題。看看這個答案here

基本上有2種不同的算法用於MySql中的視圖:合併和可暫時性。合併通常表現相當好,但Temptable可能表現不佳。當視圖包含GROUP BY的某些構造時,不能使用合併,因此您的視圖將使用Temptable算法。