処理に時間がかかるため、次のクエリをリファクタリングしたいと思います。
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 |
+----+-------------+--------------+--------+---------------+---------+---------+----------------------+-------+---------------------------------+
クエリは、タグが 2 つある場合は 17 秒、タグがWHERE IN
1 つの場合は 0.009 秒かかります。クエリを最適化する最良の方法は何ですか?