我使用以下 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 行。
索引
有什么办法可以让这个查询更高效吗?
最佳答案
你们都使用Recepient_ID
加入并按它分组,但它没有索引,所以我认为这就是问题所在。
尝试添加 transactions.Recepient_ID
作为索引。
关于mysql - 如何优化在 130,000 行上运行的联接查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14479525/