MySql未使用索引。

huangapple go评论59阅读模式
英文:

MySql not using an index

问题

DB引擎是MySql 8。
我正在运行一个简单的查询,查询的表上有一个id列的索引,但它没有使用索引,而是进行了全表扫描。

该表的统计信息已更新,id列是整数,索引也是整数。

我不想更改查询并使用强制索引,在MariaDB中它正确地使用了索引。

以下是解释计划:

1	SIMPLE	user_actions		ALL	index_id				558242932	0.0	Using where; Using parallel query (2 columns, 1 filters, 1 exprs; 0 extra)
1	SIMPLE	user_actions		eq_ref	PRIMARY	PRIMARY	8	db.user_actions.id	1	100.0	

我已经收集了统计信息,并期望优化器在where子句使用“id in (3,5,7,34,56)”进行筛选时使用索引。

英文:

DB engine is MySql 8.
I am running a simple query on a table that has an index on id column however its not using the index and its doing a full table scan.

The table has statistics updated the column of id is int and the index is also on int.

I dont want to change the query and use force index and in Maria db it is using the index correctly.

Here is the explain plan:

1	SIMPLE	user_actions		ALL	index_id				558242932	0.0	Using where; Using parallel query (2 columns, 1 filters, 1 exprs; 0 extra)
1	SIMPLE	user_actions		eq_ref	PRIMARY	PRIMARY	8	db.user_actions.id	1	100.0	

I have gathered stats and expected that the optimizer will use the index while the where clause is filtering by this column using " id in (3,5,7,34,56)

答案1

得分: 1

以下是翻译好的部分:

你从未包含你实际的SQL查询,但出于这个答案的目的,我将假设你的查询看起来像这样:

SELECT *
FROM yourTable
WHERE id IN (3, 5, 7, 34, 56);

这与以下查询相同:

SELECT *
FROM yourTable
WHERE id = 3 OR id = 5 OR id = 7 OR id = 34 OR id = 56;

WHERE子句中使用OR条件的查询很难使其适用于索引。这样的查询可能不会使用id上的索引,因为这要么需要为每个值执行多次索引查找,要么需要执行一次完整的索引扫描。在任何情况下,MySQL可能会决定扫描整个表,这似乎是你的查询计划所表明的情况。

英文:

You never included your actual SQL query, but for the purpose of this answer, I will assume your query looks something like:

<!-- language: sql -->

SELECT *
FROM yourTable
WHERE id IN (3, 5, 7, 34, 56);

This is the same as:

<!-- language: sql -->

SELECT *
FROM yourTable
WHERE id = 3 OR id = 5 OR id = 7 OR id = 34 OR id = 56;

Queries with OR conditions in the WHERE clause are hard to make amenable to index use. Such a query will probably not use an index on id, because doing so would either require several index seeks for each value, or a single full index scan. In either case, MySQL might just decide to scan the entire table, which is what your query plan seems to be saying.

huangapple
  • 本文由 发表于 2023年5月10日 23:40:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76220338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定