如何优化在130,000行上运行的联接查询?

时间:2013-01-23 12:16:29

标签: mysql performance

我正在使用以下SQL语句:

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...

transactions表中有 130,000行


学生采用以下形式:

Frog_ID UPN             Firstname   Surname     Intake_Year
101234  K929221234567   Madeup      Student     2010

student表中有 835行


索引

transactions indexes

student indexes


有没有办法让这个查询更有效率?

1 个答案:

答案 0 :(得分:2)

你们都使用Recepient_ID加入并按照它进行分组,但它没有编入索引,所以我认为这就是问题所在。

尝试添加transactions.Recepient_ID作为索引。

相关问题