2013-01-23 20 views
2

我使用下面的SQL語句:如何優化在130,000行上運行的聯接查詢?

SELECT 
    SUM(t.Points) AS `Points`, 
    CONCAT(s.Firstname, " ", s.Surname) AS `Name` 
FROM transactions t 
INNER JOIN student s 
    ON t.Recipient_ID = s.Frog_ID 
GROUP BY t.Recipient_ID 

的查詢需要21秒運行。相反,即使我LIMIT 0, 30仍然需要20.7秒運行!

如果我跑這句話的EXPLAIN,結果如下:

id select_type table type possible_keys key  key_len  ref  rows  Extra 
1 SIMPLE  s  ALL  PRIMARY   NULL NULL  NULL 877   Using temporary; Using filesort 
1 SIMPLE  t  ALL  NULL   NULL NULL  NULL 135140  Using where 

事務採用以下形式:

Transaction_ID Datetime Giver_ID Recipient_ID Points Category_ID  Reason 
1    2011-09-07 36754  34401   5  6    Gave excellent feedback on the new student noteboo... 

130000行transactions表。


學生採用以下形式:

Frog_ID UPN    Firstname Surname  Intake_Year 
1K929221234567 Madeup  Student  2010 

835排在student


指標

transactions indexes

student indexes


有沒有一種辦法可以讓這個查詢更有效?

+1

你有什麼指數? – h2ooooooo

+2

具體而言,您是否在transaction.Recipient_ID列上有索引? – Perception

+0

我已經更新了我的OP - 抱歉,認爲'EXPLAIN'可能已經足夠了(我缺乏知識)。 – dunc

回答

2

你們都加入使用Recepient_ID和它的組,但它沒有索引,所以我認爲這是問題。

嘗試添加transactions.Recepient_ID作爲索引。

+1

這太奇妙了 - 將查詢減少到1.5秒。還有什麼你可以建議進一步減少它還是我會得到最好的? – dunc

+2

花一些時間思考爲什麼有人會想要一次查看所有數據。 – symcbean

+0

當然你是對的@symcbean。我將完全想到一個新問題。 – dunc