SQL WHERE IN需要很长时间来处理SELECT语句

时间:2013-01-05 19:24:55

标签: mysql sql query-optimization

我想重构以下查询,因为它需要一段时间来处理:

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。什么是优化查询的最佳方法?

2 个答案:

答案 0 :(得分:1)

尝试在user_tags.item_id和user_products.item_id上添加索引

答案 1 :(得分:0)

MySQL应该在in语句中处理一组常量。您是否独立定时查询每个标签?其中一个标签可能包含大量数据。

如果你在tags.title上有一个索引,它可能也会有所帮助。