我试图避免文件排序,但没有从内部查询中删除它。如果我将条件移动到外部查询,那么它什么也不会显示。
Create table articles (
article_id Int UNSIGNED NOT NULL AUTO_INCREMENT,
editor_id Int UNSIGNED NOT NULL,
published_date Datetime,
Primary Key (book_id)) ENGINE = InnoDB;
Create Index published_date_INX ON articles (published_date);
Create Index editor_id_INX ON articles (editor_id);
EXPLAIN SELECT article_id, article_date FROM articles AA INNER JOIN
(
SELECT article_id
FROM articles
WHERE editor_id=1
ORDER BY published_date DESC
LIMIT 100, 5
) ART USING (article_id);
+----+-------------+------------+--------+---------------+-----------+---------+----------------+--------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+--------+---------------+-----------+---------+----------------+--------+----------------+
| 1 | | PRIMARY | <derived2> | ALL | NULL | NULL | NULL NULL | 5 | |
| 1 | | PRIMARY | AA | eq_ref | PRIMARY | PRIMARY | 4 ART.article_id | 1 | |
| 2 | | DERIVED | articles | ALL | editor_id | editor_id | 5 | 114311 | Using filesort |
+----+-------------+------------+--------+---------------+-----------+---------+----------------+--------+----------------+
3 rows in set (30.31 sec)
关于如何从此查询中删除文件排序有什么建议吗?
最佳答案
也许您可以尝试在 editor_id, published_date
上添加索引。
create index edpub_INX on articles (editor_id, published_date);
在你的内部查询中:
SELECT article_id
FROM articles
WHERE editor_id=1
ORDER BY published_date DESC
LIMIT 100, 5
MySQL 的查询规划器可能认为按 editor_id
过滤(使用索引)然后按 published_date
排序比使用 published_date_INX
更好,并且然后按 editor_id
过滤。查询规划器可能是正确的。
因此,如果您想“帮助”该特定查询,请在 editor_id, published_date
上创建一个索引,看看它是否有助于您的查询运行得更快。
关于MySQL 避免在内部查询中进行文件排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7454890/