简体   繁体   English

优化MySql查询以避免使用“使用filesort”

[英]Optimizing MySql query to avoid using “Using filesort”

I need your help to optimize the query to avoid using "Using filesort".The job of the query is to select all the articles that belongs to specific tag. 我需要你的帮助来优化查询以避免使用 “使用filesort”。查询的工作是选择属于特定标签的所有文章。 The query is: 查询是:

  select title 
    from tag,
         article 
   where tag = 'Riyad' 
     AND tag.article_id = article.id 
order by tag.article_id

The tables structure are the following: 表结构如下:

Tag table 标签表

 CREATE TABLE `tag` (
 `tag` VARCHAR( 30 ) NOT NULL ,
 `article_id` INT NOT NULL ,
 KEY `tag` (`tag`),
 KEY `article_id` (`article_id`)
 ) ENGINE = MYISAM ;

Article table 条款表

 CREATE TABLE `article` (
 `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
 `title` VARCHAR( 60 ) NOT NULL
 ) ENGINE = MYISAM 

Sample data 样本数据

 INSERT INTO `article` VALUES (1, 'About Riyad');
 INSERT INTO `article` VALUES (2, 'About Newyork');
 INSERT INTO `article` VALUES (3, 'About Paris');
 INSERT INTO `article` VALUES (4, 'About London');

 INSERT INTO `tag` VALUES ('Riyad', 1);
 INSERT INTO `tag` VALUES ('Saudia', 1);
 INSERT INTO `tag` VALUES ('Newyork', 2);
 INSERT INTO `tag` VALUES ('USA', 2);
 INSERT INTO `tag` VALUES ('Paris', 3);
 INSERT INTO `tag` VALUES ('France', 3);

In table tag , replace the key on tag with a key on ( tag , article_id ): 在表tag ,使用键( tagarticle_id )替换tag上的键:

ALTER TABLE `tag` DROP INDEX `tag`, ADD INDEX `tag_article_id` (`tag`, `article_id`)

MySQL will only use one index on a table to perform a query. MySQL只会在表上使用一个索引来执行查询。 At present, it is using the index on tag , but cannot use the other index to perform the ORDER BY. 目前,它正在使用tag上的索引,但不能使用其他索引来执行ORDER BY。 If you put the second column in the index then it will use it to help with the ORDER BY. 如果您将第二列放在索引中,那么它将使用它来帮助ORDER BY。

You're joining, in part, on tag.article_id=article.id , but don't have an index in place on the tag side to support that optimally. 你部分地加入了tag.article_id=article.id ,但是在标签方面没有一个索引可以最佳地支持。 Add a secondary (non-unique) index on tag.article_id . tag.article_id上添加辅助(非唯一)索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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