Reputation: 2352
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?
Upvotes: 0
Views: 63
Reputation: 10236
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);
Upvotes: 2
Reputation: 3806
Use EXPLAIN to obtain the query execution plan. Then, look the more consuming steps and use index if necessary.
Upvotes: 0