2013-01-05 115 views
0

我想重构下面的查询,因为它需要一些时间来处理:SQL凡在花费很长的时间来处理SELECT语句

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有一个标签。什么是优化查询的最佳方式?

+0

您是否尝试过分裂凡在分成不同的WHERE或从句? – travega

+1

在连接中使用的列上是否有索引? –

+0

也许一个解释没有在哪里部分可能是有用的比较 – biziclop

回答

1

尝试增加对user_tags.item_id指数也user_products.item_id

+0

谢谢,这是我需要做的。我也从''user_tags'.'tag_id''丢失了一个 – xylar

0

MySQL应该在in语句中处理一组常量。你是否为每个标签独立计时?其中一个标签可能有很多数据。

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

+0

刚刚试过查询每个标签,他们都回到0.2以下。 'tags.title'上有一个唯一的索引。 – xylar

+0

我会好奇别人想出什么。显然,这在某种程度上触发了低劣的执行计划。统计数据是否最新? –