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
用户。有什么想法吗?
答案 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获取查询执行计划。然后,查看更多消耗步骤并在必要时使用索引。