我在 products 表上有索引:
- 主要
- products_gender_id_foreign
- products_subcategory_id_foreign
- idx_products_cat_subcat_gender_used (多列索引)
查询:
select `id`, `name`, `price`, `images`, `used`
from `products`
where `category_id` = '1' and
`subcategory_id` = '2' and
`gender_id` = '1' and
`used` = '0'
order by `created_at` desc
limit 24 offset 0
问题:
mysql为什么要使用索引
products_subcategory_id_foreign
代替
idx_products_cat_subcat_gender_used (multiple column index)
这里是解释:
1 SIMPLE products NULL ref products_gender_id_foreign,products_subcategory_id... products_subcategory_id_foreign 5 const 2 2.50 Using index condition; Using where; Using filesort
最佳答案
如 MySQL documentation 中所述, 在某些情况下可以忽略索引。可能适用于您的情况的是:
您正在将索引列与常量值进行比较,而 MySQL 已经 计算(基于索引树)常量也覆盖 表的很大一部分,并且表扫描会更快。看 第 8.2.1.1 节,“WHERE 子句优化”。
您正在使用低基数的键(许多行与键匹配 值)通过另一列。在这种情况下,MySQL 假定通过 使用 key 它可能会做很多关键查找和一个表 扫描会更快。
我的猜测是 category_id 的值不够稀疏
关于Mysql多列索引使用错误的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51903500/