I have a view which is defined as a SELECT bellow. Is there any way to optimize this? Right now it is very very slow.
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 will return something like:
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
You could make a “result table” where you insert the result of your query into. You project reads its data from that result tabel. Then you create a job (not sure what the mysql options are) that runs the slow query every hour/day/week to keep the result table up to date.
furthermore the usual stuff like indexs