2011-09-17 60 views
1

我試圖避免使用filesort,但沒有從內部查詢中移除它。如果我將條件移動到外部查詢,那麼它不會顯示任何內容。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) 

任何建議如何從此查詢中刪除filesort?

回答

3

也許你可以嘗試添加一個索引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創建一個索引,看看它是否有助於您的查詢的運行速度。

+0

'edpub_INX'指數可能不會幫助** **的MySQL到** **排序上'published_date'因爲在B +樹索引,順序非常重要,而你的索引鍵是:'editor_id'第一和' published_date'之後。爲了幫助'order by'子句,我認爲查詢規劃器需要一個索引,其中'published_date'是它的第一個字段。 –