我在向表中添加新索引时遇到了一些问题,我想知道为什么MySQL没有使用新索引.
我注意到,只有当我的SELECT语句请求其他不属于索引的列时才会发生这种情况(例如,SELECT *
不起作用,而SELECT id, otherId
起作用).
有人能给我解释一下为什么MySQL Select 进行表扫描而不是使用索引吗?
架构数据库数据库
该表由多个列组成,即id
和otherId
.id
是我的主键,而otherId
也应该被编入索引.otherId
可以为空并且是唯一的.
model Entity {
id String @id @default(cuid())
otherId String? @unique
// Few more ...
}
基数和 Select 性
SELECT
COUNT(DISTINCT Entity.otherId) as cardinality,
COUNT(*) as totalRows,
COUNT(Entity.otherId) as nonNullRows,
COUNT(DISTINCT Entity.otherId) / COUNT(*) as selectivity
FROM
Entity
cardinality | totalRows | nonNullRows | selectivity |
---|---|---|---|
171 | 1187 | 171 | 0.1441 |
展开SELECT*
这个没有使用索引,但我希望它会使用.
展开SELECT* FROM Entity WHERE Entity.otherId = ?;
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
---|---|---|---|---|---|---|---|---|---|---|---|
1 | SIMPLE | Entity | ALL | Entity_otherId_key | 1187 | 10 | Using where |
解释SELECT ID、OtherID
这本书确实使用了索引.
解释SELECT ID、OtherID FROM Entity WHERE Entity.otherId = ?;
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
---|---|---|---|---|---|---|---|---|---|---|---|
1 | SIMPLE | Entity | index | Entity_otherId_key | Entity_otherId_key | 767 | 1187 | 10 | Using where; Using index |
显示索引
显示索引 from Entity;
Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Entity | 0 | PRIMARY | 1 | id | A | 1187 | BTREE | YES | ||||||
Entity | 0 | Entity_otherId_key | 1 | otherId | A | 172 | YES | BTREE | YES |
MySQL版本
8.2.0