我想重构以下查询,因为它需要一段时间来处理:
SELECT `user_product`.* FROM `user_products` AS `user_product`
INNER JOIN `items` ON (`user_product`.`item_id` = `items`.`id`)
INNER JOIN `user_tags` ON (`items`.`id` = `user_tags`.`item_id`)
INNER JOIN `tags` ON (`user_tags`.`tag_id` = `tags`.`id`)
WHERE `tags`.`title` IN ('tag3', 'tag')
GROUP BY `items`.`id`
ORDER BY `items`.`created_at` DESC
当我EXPLAIN
得到以下结果时:
+----+-------------+--------------+--------+---------------+---------+---------+----------------------+-------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------------+--------+---------------+---------+---------+----------------------+-------+---------------------------------+
| 1 | SIMPLE | user_tags | ALL | NULL | user_id | 12 | NULL | 27802 | Using temporary; Using filesort |
| 1 | SIMPLE | user_product | ALL | NULL | NULL | NULL | NULL | 22676 | Using where; Using join buffer |
| 1 | SIMPLE | items | eq_ref | PRIMARY | PRIMARY | 4 | user_product.item_id | 1 | Using where |
| 1 | SIMPLE | tags | eq_ref | PRIMARY,title | PRIMARY | 4 | user_tags.tag_id | 1 | Using where |
+----+-------------+--------------+--------+---------------+---------+---------+----------------------+-------+---------------------------------+
查询需要 17 秒,其中有两个标签,WHERE IN
而 0.009 有一个。优化查询的最佳方法是什么?