Slow query when using ORDER BY

2019-01-03 10:39发布

Here's the query (the largest table has about 40,000 rows)

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

If I run this, it executes very quickly (.05 seconds roughly). It returns 13 rows.

When I add an ORDER BY clause at the end of the query (ordering by any column) the query takes about 10 seconds.

I'm using this database in production now, and everything is working fine. All my other queries are speedy.

Any ideas of what it could be? I ran the query in MySQL's Query Browser, and from the command line. Both places it was dead slow with the ORDER BY.

EDIT: Tolgahan ALBAYRAK solution works, but can anyone explain why it works?

7条回答
做个烂人
2楼-- · 2019-01-03 11:12

You are selecting from "UserCourse" which I assume is a joining table between courses and users (Many to Many). You should index the column that you need to order by, in the "UserCourse" table.

Suppose you want to "order by CourseID", then you need to index it on UserCourse table.

Ordering by any other column that is not present in the joining table (i.e. UserCourse) may require further denormalization and indexing on the joining table to be optimized for speed; In other words, you need to have a copy of that column in the joining table and index it.

P.S. The answer given by Tolgahan Albayrak, although correct for this question, would not produce the desired result, in cases where one is doing a "LIMIT x" query.

查看更多
登录 后发表回答