2014-01-10 299 views
0
SELECT 
    (UserCourseProgress.TimeEnded - UserCourseProgress.TimeStarted) as SecondsSpent, 
    UserCourseProgress.UserId 
FROM 
    UserCourseProgress 
    INNER JOIN UserRoles 
    ON UserCourseProgress.UserId = UserRoles.UserId 
     AND (UserRoles.SuperId = '123' OR UserRoles.UserId = '123') 

我想優化這個查詢,因爲它需要很長時間(主要是將數據複製到Tmp表)。 該結構很簡單,一個名爲UserCourseProgress的表和另一個名爲UserRoles的表,他們都有UserId列的共同點,並且我選擇屬於超級用戶的所有userRoles。有任何想法嗎?MySQL優化查詢

+0

確保您有'UserRoles.SuperId'和'UserRoles.UserId'指標,以及如在FK UserCourseProgress.UserId' – StuartLC

+1

你可以給表結構,並且很少更多解釋, – Lijo

回答

2

使用UNION

SELECT 
    (UserCourseProgress.TimeEnded - UserCourseProgress.TimeStarted) as SecondsSpent, 
    UserCourseProgress.UserId FROM UserCourseProgress 
INNER JOIN UserRoles ON UserCourseProgress.UserId = UserRoles.UserId 
    AND UserRoles.SuperId = '123' 

UNION 

SELECT 
    (UserCourseProgress.TimeEnded - UserCourseProgress.TimeStarted) as SecondsSpent, 
    UserCourseProgress.UserId FROM UserCourseProgress 
INNER JOIN UserRoles ON UserCourseProgress.UserId = UserRoles.UserId 
    AND UserRoles.UserId = '123'; 

添加索引

ALTER TABLE UserCourseProgress ADD INDEX (UserId); 
ALTER TABLE UserRoles ADD INDEX (SuperId, UserId); 
ALTER TABLE UserRoles ADD INDEX (UserId); 
+0

工作完美! – matt

0

使用EXPLAIN獲取查詢執行計劃。然後,看看更耗費的步驟,並在必要時使用索引。

EXPLAIN