2010-06-10 8 views
8

Je suis en train d'optimiser cette requête:Mysql requête lente: INNER JOIN + ORDER BY les causes filesort

 
SELECT `posts`.* FROM `posts` INNER JOIN `posts_tags` 
    ON `posts`.id = `posts_tags`.post_id 
    WHERE (((`posts_tags`.tag_id = 1))) 
    ORDER BY posts.created_at DESC; 

La taille des tables est 38k lignes et 31k et MySQL utilise "filesort" il devient assez lent. J'ai essayé d'utiliser différents index, pas de chance.

 
CREATE TABLE `posts` (
    `id` int(11) NOT NULL auto_increment, 
    `created_at` datetime default NULL, 
    PRIMARY KEY (`id`), 
    KEY `index_posts_on_created_at` (`created_at`), 
    KEY `for_tags` (`trashed`,`published`,`clan_private`,`created_at`) 
) ENGINE=InnoDB AUTO_INCREMENT=44390 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci 

CREATE TABLE `posts_tags` (
    `id` int(11) NOT NULL auto_increment, 
    `post_id` int(11) default NULL, 
    `tag_id` int(11) default NULL, 
    `created_at` datetime default NULL, 
    `updated_at` datetime default NULL, 
    PRIMARY KEY (`id`), 
    KEY `index_posts_tags_on_post_id_and_tag_id` (`post_id`,`tag_id`) 
) ENGINE=InnoDB AUTO_INCREMENT=63175 DEFAULT CHARSET=utf8 
 
+----+-------------+------------+--------+--------------------------+--------------------------+---------+---------------------+-------+-----------------------------------------------------------+ 
| id | select_type | table  | type | possible_keys   | key      | key_len | ref     | rows | Extra              | 
+----+-------------+------------+--------+--------------------------+--------------------------+---------+---------------------+-------+-----------------------------------------------------------+ 
| 1 | SIMPLE  | posts_tags | index | index_post_id_and_tag_id | index_post_id_and_tag_id | 10  | NULL    | 24159 | Using where; Using index; Using temporary; Using filesort | 
| 1 | SIMPLE  | posts  | eq_ref | PRIMARY     | PRIMARY     | 4  | .posts_tags.post_id |  1 |               | 
+----+-------------+------------+--------+--------------------------+--------------------------+---------+---------------------+-------+-----------------------------------------------------------+ 
2 rows in set (0.00 sec) 

Quel genre d'indice que je dois définir pour éviter MySQL avec filesort? Est-il possible lorsque le champ de commande n'est pas dans la clause where?

mise à jour: résultats Profilage:

 
mysql> show profile for query 1; 
+--------------------------------+----------+ 
| Status       | Duration | 
+--------------------------------+----------+ 
| starting      | 0.000027 | 
| checking query cache for query | 0.037953 | 
| Opening tables     | 0.000028 | 
| System lock     | 0.010382 | 
| Table lock      | 0.023894 | 
| init       | 0.000057 | 
| optimizing      | 0.010030 | 
| statistics      | 0.000026 | 
| preparing      | 0.000018 | 
| Creating tmp table    | 0.128619 | 
| executing      | 0.000008 | 
| Copying to tmp table   | 1.819463 | 
| Sorting result     | 0.001092 | 
| Sending data     | 0.004239 | 
| end       | 0.000012 | 
| removing tmp table    | 0.000885 | 
| end       | 0.000006 | 
| end       | 0.000005 | 
| query end      | 0.000006 | 
| storing result in query cache | 0.000005 | 
| freeing items     | 0.000021 | 
| closing tables     | 0.000013 | 
| logging slow query    | 0.000004 | 
| cleaning up     | 0.000006 | 
+--------------------------------+----------+ 

Update2:

requête Real (certains champs plus booléennes, plusieurs index inutiles)

SELECT `posts`.* FROM `posts` INNER JOIN `posts_tags` 
    ON `posts`.id = `posts_tags`.post_id 
    WHERE ((`posts_tags`.tag_id = 7971)) 
     AND (((posts.trashed = 0) 
     AND (`posts`.`published` = 1 
     AND `posts`.`clan_private` = 0)) 
     AND ((`posts_tags`.tag_id = 7971))) 
    ORDER BY created_at DESC LIMIT 0, 10;

ensemble vide (1,25 sec)

Avec sur COMMANDEZ PAR - 0.01s.

 

+----+-------------+------------+--------+-----------------------------------------+-----------------------+---------+---------------------+-------+--------------------------+ 
| id | select_type | table  | type | possible_keys       | key     | key_len | ref     | rows | Extra     | 
+----+-------------+------------+--------+-----------------------------------------+-----------------------+---------+---------------------+-------+--------------------------+ 
| 1 | SIMPLE  | posts_tags | index | index_posts_tags_on_post_id_and_tag_id | index_posts_tags_... | 10  | NULL    | 23988 | Using where; Using index | 
| 1 | SIMPLE  | posts  | eq_ref | PRIMARY,index_posts_on_trashed_and_crea | PRIMARY    | 4  | .posts_tags.post_id |  1 | Using where    | 
+----+-------------+------------+--------+-----------------------------------------+-----------------------+---------+---------------------+-------+--------------------------+ 

SOLUTION

  1. de requête mis à jour "ORDER BY posts_tags.created_at DESC" (deux petits changements dans le code de l'application)
  2. Index ajouté: index_posts_tags_on_created_at.

C'est tout!

Répondre

3

Vous devrez dénormaliser un peu, et copiez le champ posts.created_at dans la table post_tags (je l'ai appelé post_created_at, vous pouvez nommer comment vous voulez):

CREATE TABLE `posts_tags` (
    `id` int(11) NOT NULL auto_increment, 
    `post_id` int(11) default NULL, 
    `tag_id` int(11) default NULL, 
    `post_created_at` datetime default NULL, 
    `created_at` datetime default NULL, 
    `updated_at` datetime default NULL, 
    PRIMARY KEY (`id`), 
    KEY `index_posts_tags_on_post_id_and_tag_id` (`post_id`,`tag_id`) 
) ENGINE=InnoDB; 

puis ajouter un index à posts_tags sur

(tag_id, post_created_at) 

qui permettra à la requête pour obtenir tous les postes pour une étiquette, dans l'ordre, sans filesort.

+0

Merci! J'ai mis à jour la requête pour utiliser posts_tags.created_at pour le tri (pas besoin de connaître la date de création de balise) et ajouté index_posts_tags_on_created_at ... plus de fichiers! :) – Alexander

+0

Est-il possible d'informer le planificateur de requêtes que deux colonnes dans des tables différentes sont identiques, vous n'avez donc pas besoin de spécifier explicitement qu'il doit utiliser posts_tags.created_at au lieu de posts.created_at? – sorenbs

0

votre clé index_posts_on_created_at est ascendante mais vous triés veulent des résultats classés décroissant

+0

Il utilise filesort avec les ordres de tri ASC et DESC :( – Alexander

1

Essayez de changer KEY index_posts_tags_on_post_id_and_tag_id (post_id, tag_id) à KEY index_posts_tags_tag_id (tag_id) et rediffuser Expliquer.

Quelle est la distribution des TagID avec Posts_Tags?