2013-08-24 183 views
0

我使用以下mysql查詢來獲取一些期望的結果,但問題是它需要更多時間。目前這個查詢的執行時間是7456毫秒這是我的項目無法接受的,我想優化這個查詢任何想法?mysql查詢優化左連接

SELECT *, DATEDIFF(NOW(),ticketstatus_tbl.updation_date) AS problem_age,images_tbl.image_path 
      FROM ticketstatus_tbl 
      LEFT JOIN question_tbl ON ticketstatus_tbl.question_id = question_tbl.question_id 
      LEFT JOIN ticketing_tbl ON ticketstatus_tbl.related_ticket_id = ticketing_tbl.ticket_id 
      LEFT JOIN department_tbl ON question_tbl.question_dept = department_tbl.department_id 
      LEFT JOIN branch_tbl ON ticketstatus_tbl.branch_id = branch_tbl.id 
      LEFT JOIN images_tbl ON images_tbl.question_id = ticketstatus_tbl.question_id and images_tbl.branch_id = ticketstatus_tbl.branch_id 
      WHERE (ticketstatus_tbl.ticket_status NOT IN ('Close') 
      AND question_tbl.is_active_question = 1 
      AND ticketstatus_tbl.display_status = '1' 
      AND ticketstatus_tbl.flag_color = 'Yellow' 
      AND department_tbl.department_name = 'Admin')order by ticket_number ASC LIMIT 0 ,5 

感謝

+0

請張貼你在表格上的索引和查詢的解釋。 –

+0

表結構和EXPLAIN輸出,或者不期望有意義的答案。 http://dev.mysql.com/doc/refman/5.6/en/explain.html – Mchl

+0

將索引放在ON子句中使用的列上通常會幫助很多人。當然,你在數據庫中沒有其他奇怪的事情發生。這就是爲什麼我們可能需要更多信息來幫助你。 – Hless

回答

2

首先,你並不需要所有的left outer join,因爲你的where子句撤銷其中的大多數。我的猜測是所有可以變成內部連接,但在最低限度:

SELECT *, DATEDIFF(NOW(),ticketstatus_tbl.updation_date) AS problem_age,images_tbl.image_path 
FROM ticketstatus_tbl 
      JOIN question_tbl ON ticketstatus_tbl.question_id = question_tbl.question_id 
      LEFT JOIN ticketing_tbl ON ticketstatus_tbl.related_ticket_id = ticketing_tbl.ticket_id 
      JOIN department_tbl ON question_tbl.question_dept = department_tbl.department_id 
      LEFT JOIN branch_tbl ON ticketstatus_tbl.branch_id = branch_tbl.id 
      LEFT JOIN images_tbl ON images_tbl.question_id = ticketstatus_tbl.question_id and images_tbl.branch_id = ticketstatus_tbl.branch_id 
WHERE ticketstatus_tbl.ticket_status NOT IN ('Close') 
      AND question_tbl.is_active_question = 1 
      AND ticketstatus_tbl.display_status = '1' 
      AND ticketstatus_tbl.flag_color = 'Yellow' 
      AND department_tbl.department_name = 'Admin' 
order by ticket_number ASC LIMIT 0 ,5; 

其次,你正在做的ticketstatus_tbl過濾。你應該在ticketstatus_tbl(display_status, flag_color, ticket_status, question_id)上有一個複合索引。如果可以,請將ticket_status not in ('Close')更改爲肯定性聲明:ticket_status in (打開, 'In Progress', . . .)。這使得索引更容易使用。

這是一個開始。

+0

grt :)戈登你的訣竅實際上問題是在images_tbl。它包含將近15,000行,並且我正在執行左連接,導致執行時間很長。現在使用內部連接和images_tbl執行時間降至300毫秒。謝謝 –

+0

@DineshNagar如果這個答案解決了你的問題,請選擇它作爲正確的答案。如果沒有,或者您想添加它,請添加您自己的答案,並選擇該答案作爲您的首選答案。 – Technoh