我想重构下面的查询,因为它需要一些时间来处理: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有一个标签。什么是优化查询的最佳方式?
您是否尝试过分裂凡在分成不同的WHERE或从句? – travega
在连接中使用的列上是否有索引? –
也许一个解释没有在哪里部分可能是有用的比较 – biziclop