MySQL 避免在内部查询中进行文件排序

标签 mysql filesort

我试图避免文件排序,但没有从内部查询中删除它。如果我将条件移动到外部查询,那么它什么也不会显示。

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/

相关文章:

java - 从 MySQL 中检索 double 值

mysql - 如何避免此 mysql 查询的文件排序

mysql - 使用索引,使用临时,使用文件排序 - 如何解决这个问题?

mysql - 另一个按 Order By MySQL 查询分组

mysql - 使用 concat 和 filesort 时 mysql 查询速度变慢

mysql - 由于索引无效而避免文件排序..?

php - 使用子查询中的计数来确定行是否应包含在结果行中

c++ - 如何使用 MySQL 连接器在 C++ 中防止打开文件过多

MySQL DELETE - 此版本的 MySQL 尚不支持 'LIMIT & IN/ALL/ANY/SOME subquery'

mysql - SQL:如何使用相应的外键为表中的每个现有元素插入一行到表中?