gpt4 book ai didi

MySql 索引不适用于 GROUP BY

转载 作者:行者123 更新时间:2023-11-29 18:57:12 26 4
gpt4 key购买 nike

我有两个表来创建我的搜索引擎,一个包含所有关键字,另一个包含每个关键字的所有可能目标。

Table: keywords
id (int)
keyword (varchar)

Table: results
id (int)
keyword_id (int)
table_id (int)
target_id (int)

对于这两个表,我将 MyISAM 设置为存储引擎,因为 95% 的情况下我只是在这些表上运行选择查询,而 5% 的情况下是插入查询。当然,我已经比较了使用 InnoDB 的性能,考虑到我后来的查询,性能很差。

我还添加了以下索引

keywords.keyword (unique)
results.keyword_id (index)
results.table_id (index)
results.target_id (index)

关键字表中,我有大约120万条记录,在结果表中,我有大约980万条记录。

现在问题是我运行以下查询,结果在 0.0014 秒内生成

SELECT rs.table_id, rs.target_id
FROM keywords ky INNER JOIN results rs ON ky.id=rs.keyword_id
WHERE ky.keyword LIKE "x%" OR ky.keyword LIKE "y%"

但是当我添加GROUP BY时,结果是在0.2秒内得出的

SELECT rs.table_id, rs.target_id
FROM keywords ky INNER JOIN results rs ON ky.id=rs.keyword_id
WHERE ky.keyword LIKE "x%" OR ky.keyword LIKE "y%"
GROUP BY rs.table_id, rs.target_id

我测试了复合索引、单列索引,甚至删除了 table_id 和 target_id 索引,但在所有情况下性能都是相同的,并且似乎在 Group By 子句中没有应用索引。

解释计划表明:

id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
1 | SIMPLE | ky | range | PRIMARY,keyword | keyword | 767 | NULL | 3271 | Using index condition; Using where; Using temporary; Using filesort
1 | SIMPLE | rs | ref | keyword_id | keyword_id | 4 | ky.id | 3

我已经添加了以下复合键

ALTER TABLE results ADD INDEX `table_id` (`table_id`, `target_id`) USING BTREE;

最佳答案

Here's MySQL文档中关于GROUP BY优化的内容是这样的:

The most important preconditions for using indexes for GROUP BY are that all GROUP BY columns reference attributes from the same index

因此,如果这两列有不同的索引,GROUP BY 将不会使用它们。您应该尝试在 table_idtarget_id 上创建复合索引。

此外,查询似乎正在使用 LIKE 运算符。请注意,如果 LIKE 中比较的值包含前导通配符,那么 MySQL 将无法对该列使用任何索引。查看查询的解释计划并查看使用了哪些索引。

关于MySql 索引不适用于 GROUP BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44084426/

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