Mysql slow query: INNER JOIN + ORDER BY causes filesort

前端 未结 3 1542
孤独总比滥情好
孤独总比滥情好 2020-12-19 02:27

I\'m trying to optimize this query:

SELECT `posts`.* FROM `posts` INNER JOIN `posts_tags` 
     ON `posts`.id = `posts_tags`.post_id 
     WHERE  (((`posts_tags`.         


        
相关标签:
3条回答
  • 2020-12-19 03:08

    Try changing KEY index_posts_tags_on_post_id_and_tag_id (post_id,tag_id) to KEY index_posts_tags_tag_id (tag_id) and repost Explain.

    What is the distribution of TagIDs withing Posts_Tags?

    0 讨论(0)
  • 2020-12-19 03:12

    You would need to denormalize a bit, and copy the posts.created_at field into the post_tags table (I called it post_created_at, you could name it how you want):

    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;
    

    and then add an index to posts_tags on

    (tag_id, post_created_at)
    

    That will allow the query to get all the posts for a tag, in the correct order, without filesort.

    0 讨论(0)
  • 2020-12-19 03:17

    your key index_posts_on_created_at is sorted ascending but you want results sorted descending

    0 讨论(0)
提交回复
热议问题