如何改进 MySQL 中的 SELECT 子查询?
How do I improve SELECT subquery in MySQL?
我有一个 table 学生和第二本能读的书。我正在尝试获取学生名单以及他们拥有的书籍数量。
"SELECT
StudentID,
FullName,
book_count.ct
FROM
students
LEFT JOIN (
SELECT
StudentID,
COUNT(DISTINCT id) AS ct
FROM
books
GROUP BY
StudentID
) AS book_count
ON
book_count.StudentID = students.StudentID
ORDER BY
students.FullName ASC
LIMIT 0, 30;
此查询到 运行 大约需要 6 秒,并且随着添加更多书籍,它会变得越来越慢。查看查询配置文件 >90% 的时间花在 "copying to temp table" 上。问题是我的子 select 查询获取书籍搜索的数量并计算整本书的总数 table 而不管我可能会查找多少学生,在我的例子中是 30 个。我该如何提高这方面的表现?谢谢。
试试这个:
SELECT StudentID, FullName,COUNT(books.id) AS book_count
FROM students
LEFT JOIN books ON books.StudentID = students.StudentID
GROUP BY StudentID
ORDER BY students.FullName ASC
LIMIT 0, 30;
将其更改为
"SELECT
StudentID,
FullName,
( SELECT
COUNT(id)
FROM
books
where books.StudentID = students.StudentID
) AS book_count
FROM
students
ORDER BY
students.FullName ASC
LIMIT 0, 30;"
在学生列的全名上添加索引
和书籍中的 StudentID table.
我有一个 table 学生和第二本能读的书。我正在尝试获取学生名单以及他们拥有的书籍数量。
"SELECT
StudentID,
FullName,
book_count.ct
FROM
students
LEFT JOIN (
SELECT
StudentID,
COUNT(DISTINCT id) AS ct
FROM
books
GROUP BY
StudentID
) AS book_count
ON
book_count.StudentID = students.StudentID
ORDER BY
students.FullName ASC
LIMIT 0, 30;
此查询到 运行 大约需要 6 秒,并且随着添加更多书籍,它会变得越来越慢。查看查询配置文件 >90% 的时间花在 "copying to temp table" 上。问题是我的子 select 查询获取书籍搜索的数量并计算整本书的总数 table 而不管我可能会查找多少学生,在我的例子中是 30 个。我该如何提高这方面的表现?谢谢。
试试这个:
SELECT StudentID, FullName,COUNT(books.id) AS book_count
FROM students
LEFT JOIN books ON books.StudentID = students.StudentID
GROUP BY StudentID
ORDER BY students.FullName ASC
LIMIT 0, 30;
将其更改为
"SELECT
StudentID,
FullName,
( SELECT
COUNT(id)
FROM
books
where books.StudentID = students.StudentID
) AS book_count
FROM
students
ORDER BY
students.FullName ASC
LIMIT 0, 30;"
在学生列的全名上添加索引 和书籍中的 StudentID table.