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')

I'm trying to optimise this query as it takes too long (mainly Copying Data To Tmp Table). The structure is simple a table called UserCourseProgress and another one called UserRoles, they both have the UserId column in common and I'm selecting all userRoles that belong to a super user. Any ideas?

2
  • Make sure you have indexes on UserRoles.SuperId and UserRoles.UserId, as well as on the FK UserCourseProgress.UserId Commented Jan 10, 2014 at 12:53
  • 1
    can you give the table structure ,and little more explanation, Commented Jan 10, 2014 at 12:57

2 Answers 2

2

Use 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';

Add INDEX

ALTER TABLE UserCourseProgress ADD INDEX (UserId);
ALTER TABLE UserRoles ADD INDEX (SuperId, UserId);
ALTER TABLE UserRoles ADD INDEX (UserId);
Sign up to request clarification or add additional context in comments.

Comments

0

Use EXPLAIN to obtain the query execution plan. Then, look the more consuming steps and use index if necessary.

EXPLAIN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.