Mysql slow query: INNER JOIN + ORDER BY causes filesort

前端 未结 3 1547
孤独总比滥情好
孤独总比滥情好 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: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.

提交回复
热议问题