MySQL优化查询

时间:2014-01-10 12:50:47

标签: mysql query-optimization

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用户。有什么想法吗?

2 个答案:

答案 0 :(得分: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';

添加INDEX

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

答案 1 :(得分:0)

使用EXPLAIN获取查询执行计划。然后,查看更多消耗步骤并在必要时使用索引。

EXPLAIN