-2

I have sql query

SELECT 
  bd2.*, 
  bdmax.last_video, 
  bdmax.number_videos 
FROM 
  video bd2 
  JOIN 
    ( SELECT 
      bd.video_cat_id, 
      MAX(bd.last_poster_time) AS last_video, 
      COUNT(bd.video_id) as number_videos 
    FROM 
      video bd 
    GROUP BY 
      bd.video_cat_id 
    ) AS bdmax 
    ON bd2.video_cat_id = bdmax.video_cat_id 
      AND bd2.last_poster_time = bdmax.last_video;

enter image description here

Table keys are

  PRIMARY KEY (`video_id`),
  KEY `video_cat_id` (`video_cat_id`),
  KEY `video_user_id` (`video_user_id`),
  KEY `video_time` (`video_time`),
  KEY `video_urn` (`video_urn`),
  KEY `last_poster_time` (`last_poster_time`),
  KEY `video_username` (`video_username`),
  KEY `video_approval` (`video_approval`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=45619 ;

How can optimize this query to use indexes?

ADyson
  • 57,178
  • 14
  • 51
  • 63
Begemont
  • 9
  • 1

1 Answers1

0

Don't clutter things by putting the table name at the beginning of column names. Then this 'composite' index

INDEX(cat_id, last_poster_time, id)

will help the subquery (by being "covering") and the JOIN.

Part of this query is "groupwise max". But the COUNT means that optimizations for the max are not useful.

Rick James
  • 135,179
  • 13
  • 127
  • 222
  • Thank You for answer! Now table have keys PRIMARY KEY (`video_id`), KEY `video_cat_id` (`video_cat_id`), KEY `video_user_id` (`video_user_id`), KEY `video_time` (`video_time`), KEY `video_urn` (`video_urn`), KEY `last_poster_time` (`last_poster_time`), KEY `video_username` (`video_username`), KEY `video_approval` (`video_approval`), KEY `video_cat_id_2` (`video_cat_id`,`last_poster_time`,`video_id`) It's ok? https://image.ibb.co/fDo4Aw/query.jpg – Begemont Nov 08 '17 at 07:33
  • Good. But now you can get rid of `KEY video_cat_id (video_cat_id)` as being redundant (same as the left most column(s) of the new index). Does it run faster? That is the real deciding point. – Rick James Nov 08 '17 at 14:09
  • I can delete that index, and create only that You adwise, do it? – Begemont Nov 08 '17 at 14:22
  • Looks like you have already added the better index. This would remove the unnecessary one: `ALTER TABLE video DROP INDEX video_cat_id;` – Rick James Nov 08 '17 at 15:02
  • Now table have keys PRIMARY KEY (`video_id`), KEY `video_user_id` (`video_user_id`), KEY `video_time` (`video_time`), KEY `video_urn` (`video_urn`), KEY `last_poster_time` (`last_poster_time`), KEY `video_username` (`video_username`), KEY `video_approval` (`video_approval`), KEY `video_cat_id` (`video_cat_id`,`last_poster_time`,`video_id`) https://image.ibb.co/coRHfw/query.jpg Many thanks for all!!!! – Begemont Nov 08 '17 at 15:20