这是查询(最大的表约有40,000行)
SELECT Course.CourseID, Course.Description, UserCourse.UserID, UserCourse.TimeAllowed, UserCourse.CreatedOn, UserCourse.PassedOn, UserCourse.IssuedOn, C.LessonCnt FROM UserCourse INNER JOIN Course USING(CourseID) INNER JOIN ( SELECT CourseID, COUNT(*) AS LessonCnt FROM CourseSection GROUP BY CourseID ) C USING(CourseID) WHERE UserCourse.UserID = 8810
如果运行此命令,它将很快执行(大约.05秒)。它返回13行。
当我ORDER BY在查询末尾添加一个子句(按任意列排序)时,查询大约需要10秒钟。
ORDER BY
我现在正在生产中使用此数据库,并且一切正常。我所有其他查询都很快。
有什么想法吗?我在MySQL的查询浏览器中并从命令行运行了查询。两个地方都死了ORDER BY。
编辑: Tolgahan ALBAYRAK解决方案有效,但是谁能解释为什么它有效?
也许这会有所帮助:
SELECT * FROM ( SELECT Course.CourseID, Course.Description, UserCourse.UserID, UserCourse.TimeAllowed, UserCourse.CreatedOn, UserCourse.PassedOn, UserCourse.IssuedOn, C.LessonCnt FROM UserCourse INNER JOIN Course USING(CourseID) INNER JOIN ( SELECT CourseID, COUNT(*) AS LessonCnt FROM CourseSection GROUP BY CourseID ) C USING(CourseID) WHERE UserCourse.UserID = 8810 ) ORDER BY CourseID