简体   繁体   中英

MySQL avoid filesort in inner query

I am trying to avoid filesort but not getting luck in removing it from inner query. If I move condition to outer query then it shows me nothing.

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)

Any suggestion how to remove filesort from this query?

Maybe you can try adding an index on editor_id, published_date .

create index edpub_INX on articles (editor_id, published_date);

On your inner query:

SELECT article_id 
  FROM articles 
 WHERE editor_id=1 
 ORDER BY published_date DESC 
 LIMIT 100, 5

MySQL's query planner is probably thinking that filtering by editor_id (using the index) and then ordering by published_date is better than using published_date_INX and then filtering by editor_id . And query planner is probably right.

So, if you want to "help" on that specific query, create an index on editor_id, published_date and see if it helps your query run faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM