gpt4 book ai didi

MySQL相似表的索引使用不一致: 'Using index' and 'Using where; Using index'

转载 作者:行者123 更新时间:2023-11-29 17:53:40 26 4
gpt4 key购买 nike

我在优化 JOIN 以使用复合索引时遇到问题。我的查询是:

SELECT p1.id, p1.category_id, p1.tag_id, i.rating
FROM products p1
INNER JOIN (SELECT tag_id FROM tags WHERE category_id = 662) AS t
ON t.tag_id = p1.tag_id
LEFT JOIN (SELECT tax_id, rating FROM ratings WHERE category_id = 662) AS i
ON i.tax_id = p1.category_id
LIMIT 5

使用 EXPLAIN 时,INNER JOIN 只使用索引,不接触 DB,但 LEFT JOIN 返回 'Using where;使用索引':

1   SIMPLE  tags    ref PRIMARY,category_id         PRIMARY        4    const                           87  100  Using index
1 SIMPLE p1 ref category_id,category_id_2 topic_id 5 func 40 100 Using where; Using index
1 SIMPLE ratings ref category_id_2,category_id category_id 8 const,data.p1.category_id 1 100 Using where; Using index

我在所有三个表上都有覆盖索引,并且两个联接都包含 WHERE 子句。

索引:

tags(category_id, tag_id)
ratings(category_id, tax_id, rating)

为什么第一个连接仅使用索引而不使用 WHERE,如何使第二个连接执行相同操作?尝试了各种索引组合以及强制使用索引,但似乎没有任何效果。

最佳答案

查看您的代码,为了获得更好的性能,您可以使用正确的联接来避免子查询

  SELECT p1.id, p1.category_id, p1.tag_id, i.rating
FROM products p1
INNER JOIN tags t ON t.tag_id = p1.tag_id AND t.category_id = 662
LEFT JOIN ratings i ON i.tax_id = p1.category_id AND i.category_id = 662
LIMIT 5

在这里,您不必强制数据库引擎构建临时结构来管理不必要的结果

正如 juergend 在对问题的评论中所建议的,解释计划中的 where 单词仅意味着该表正在扫描过滤器

关于MySQL相似表的索引使用不一致: 'Using index' and 'Using where; Using index' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49069335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com