I have a simply query:
SELECT DISTINCT images.*
FROM `images`
WHERE `images`.`user_id` IN (SELECT following_id
FROM `follows`
WHERE `follows`.`follower_id` = 9
AND `follows`.`accepted` = 1)
LIMIT 15 offset 0
This executes in less than 1 ms.
Adding an ORDER BY on column that is indexed:
SELECT DISTINCT images.*
FROM `images`
WHERE `images`.`user_id` IN (SELECT following_id
FROM `follows`
WHERE `follows`.`follower_id` = 9
AND `follows`.`accepted` = 1)
ORDER BY id DESC
LIMIT 15 offset 0
takes 15 ms to execute. There are a mere 7,000 images in the table. Should it really take 15 fold time to order an indexed column? What can I do to decrease such a performance hit?
Running on:
Server version: 5.6.11-enterprise-commercial-advanced MySQL Enterprise Server - Advanced Edition (Commercial)
EXPLAIN:
+----+--------------+-------------+-------------+-----------------------------------+----------------------+---------+--------------------------+------+--------------------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------+-------------+-------------+-----------------------------------+----------------------+---------+--------------------------+------+--------------------------------------------------------------+
| 1 | SIMPLE | <subquery2> | ALL | NULL | NULL | NULL | NULL | NULL | Using where; Using temporary; Using filesort |
| 1 | SIMPLE | images | ref | user_id | user_id | 5 | <subquery2>.following_id | 3 | NULL |
| 2 | MATERIALIZED | follows | index_merge | accepted,follower_id,following_id | follower_id,accepted | 5,2 | NULL | 19 | Using intersect(follower_id,accepted); Using where; Distinct |
+----+--------------+-------------+-------------+-----------------------------------+----------------------+---------+--------------------------+------+--------------------------------------------------------------+
Thanks
follows
table may help.