2011-11-23 48 views
1

我有一個定義爲SELECT波紋管的視圖。有什麼辦法可以優化嗎?現在它非常緩慢。如何優化一個像這樣有很多連接的SELECT查詢?

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 (`t2`.`territoryid` = `t10`.`territoryid`)))) 
     LEFT JOIN `table11` `t11` 
      ON((`t11`.`voucherid` = `t8`.`voucherid`))) 
     LEFT JOIN `table12` `t12` 
      ON((`t12`.`orderid` = `t1`.`orderid`))) 
GROUP BY `t5`.`transactionid` 

EXPLAIN將返回類似:

id select_type table type possible_keys key key_len ref rows Extra 
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 11571 
2 DERIVED t1 ALL NULL NULL NULL NULL 11737 "Using temporary; Using filesort" 
2 DERIVED t2 eq_ref PRIMARY PRIMARY 4 database.o.userID 1 
2 DERIVED t3 ref fk_tblOrderItemLicenses_tblOrders1 fk_tblOrderItemLicenses_tblOrders1 4 database.o.orderID 1 
2 DERIVED t4 ref fk_tblOrderItemLicenseRefunds_tblOrderItemLicenses1 fk_tblOrderItemLicenseRefunds_tblOrderItemLicenses1 4 database.oil.orderItemLicenseID 1 "Using index" 
2 DERIVED t5 ref fk_tblTransactions_tblOrders1 fk_tblTransactions_tblOrders1 4 database.o.orderID 1 
2 DERIVED t6 ref fk_tblTransactionCardDetails_tblTransactions1 fk_tblTransactionCardDetails_tblTransactions1 4 database.t.transactionID 1 
2 DERIVED t7 ref fk_tblVoucherTransactions_tblTransactions1 fk_tblVoucherTransactions_tblTransactions1 4 database.t.transactionID 1 
2 DERIVED t8 eq_ref PRIMARY PRIMARY 4 database.vt.voucherID 1 
2 DERIVED t9 ref fk_tblVoucherVoucherGroups_tblVouchers1 fk_tblVoucherVoucherGroups_tblVouchers1 4 database.v.voucherID 1 "Using index" 
2 DERIVED t10 eq_ref PRIMARY PRIMARY 4 database.vvg.voucherGroupID 1 
2 DERIVED t11 ref fk_tblUserVouchers_tblVouchers fk_tblUserVouchers_tblVouchers 4 database.v.voucherID 1 "Using index" 
2 DERIVED t12 ref fk_tblTaiwanInvoiceData_tblOrders1 fk_tblTaiwanInvoiceData_tblOrders1 4 database.o.orderID 1 
+1

有什麼[解釋](http://dev.mysql.com/doc/refman/5.0/en/explain.html)輸出? –

+3

嘗試刪除所有的括號。 (是的_all_他們。) – Brian

回答

1

你可以做一個「結果記錄表」,您將您的查詢到的結果。您的項目從結果tabel中讀取其數據。然後,您創建一個每小時/每天/周運行緩慢查詢的作業(不確定mysql選項是什麼),以保持結果表處於最新狀態。

而且平常的東西像指數法

+0

這是我做了一個類似的查詢與* lot *的聯合和條件。我別無選擇,只能每天運行它並將其存儲在一張桌子上,因爲查詢會持續幾個小時運行! – DiegoDD