这个问题令我感到困惑。我真的不明白一个简单的查询如何触发临时表并执行如此糟糕的
SELECT Urls.*
FROM urls Urls
INNER JOIN categories_urls CategoriesUrls ON Urls.id = CategoriesUrls.url_id
INNER JOIN categories Categories ON Categories.id = CategoriesUrls.category_id
WHERE Categories.id = 450
AND Urls.removed = 0
AND Urls.adult = 0
AND Urls.id <> 1561806
ORDER BY Urls.sj_score DESC, Urls.average_rating DESC, Urls.num_reviews DESC
LIMIT 4
OFFSET 0
Urls有1.2M行 分类1k行 CategoriesUrls 44k行
索引需要如何才能创建临时表?我有几个类似的简单查询同样的问题。
谢谢!
答案 0 :(得分:0)
如果引擎按顺序读取表格(categories,categories_urls,urls),则没有索引可以帮助您避免&#34; filesort&#34;。
您可以尝试使用STAIGHT_JOIN
:
SELECT Urls.*
FROM urls Urls
STRAIGHT_JOIN categories_urls CategoriesUrls ON Urls.id = CategoriesUrls.url_id
WHERE CategoriesUrls.category_id = 450
AND Urls.removed = 0
AND Urls.adult = 0
AND Urls.id <> 1561806
ORDER BY Urls.sj_score DESC, Urls.average_rating DESC, Urls.num_reviews DESC
LIMIT 4
OFFSET 0
索引位于urls(adult, removed, sj_score, average_rating, num_reviews, id)
和categories_urls(url_id, category_id)
(请注意,我从查询中删除了categories
表,因为您可以使用CategoriesUrls.category_id = 450
来过滤类别。)
更多url属于指定的类别,此查询将更快找到4行并停止执行。但是如果没有足够的行,查询可能会比原来的更差。