Mysql SQL中,处理SELECT语句需要很长时间
我想重构以下查询,因为它需要一段时间来处理:Mysql SQL中,处理SELECT语句需要很长时间,mysql,sql,query-optimization,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`.
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
当我解释时,我得到以下结果:
+----+-------------+--------------+--------+---------------+---------+---------+----------------------+-------+---------------------------------+
| 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秒,其中
中有两个标记,其中中有一个标记,查询时间为0.009秒。优化查询的最佳方法是什么?MySQL应该在in
语句中处理一组常量。您是否独立地为每个标记的查询计时?其中一个标记可能包含大量数据
如果您在tags.title上有一个索引,可能也会有所帮助。尝试在user\u tags.item\u id和user\u products上添加索引。item\u id您是否尝试过将WHERE IN out拆分为单独的WHERE,或子句?在联接中使用的列上有索引吗?也许不带WHERE in部分的解释对comparison@ypercube感谢推送-在user\u tags`上使用索引速度更快。`item\u id
连接(多对多)表上的常用索引是有两个复合索引:两个(项目id,标记id)
和(标记id,项目id)
。但是您的表名表明您的设计更复杂。只需尝试查询每个标记,它们都返回到0.2以下。在标记上有一个唯一的索引。title
。我很好奇其他人会想到什么。很明显,这在某种程度上触发了一个较差的执行计划。表上的统计信息是最新的吗?谢谢,这是我的建议这就是我需要做的。我也在user\u tags`.`tag\u id