mysql - 什么是复合索引以及如何正确使用它?

标签 mysql sql indexing compound-index

我有一个非常慢的查询,它会重复很多次。我试过为各个字段编制索引,但似乎无济于事。 CPU 使用率仍然很高,查询仍然出现在慢查询日志中。看来我需要一个复合索引?

如何正确索引以下查询?

select *
from `to_attachments` left join
     `attachments`
     on `to_attachments`.`attachment_id` = `attachments`.`id`
where `to_attachments`.`object_type` = 'communicator' and `to_attachments`.`object_id` = '64328'
order by `attachments`.`created_at` desc;

解释结果: 1 SIMPLE to_attachments index NULL PRIMARY 775 NULL 244384 Using where;使用索引;使用临时的;使用文件排序 1 简单附件 eq_ref PRIMARY PRIMARY 4 quote.to_attachments.attachment_id 1 NULL

to_attachments 的索引 enter image description here

最佳答案

您需要在 to_attachments(object_type, object_id, attachment_id)attachments(id) 上建立索引。

关于mysql - 什么是复合索引以及如何正确使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52631347/

相关文章:

algorithm - 为什么不把父指针保存在 "B+ Tree",方便树向上遍历?

mysql - MySQL 表的行越多,查找行所需的时间就越长

arrays - 如何搜索 PowerShell 对象数组并检索匹配字符串的索引?

mysql - 来自已知点查询的 SQL 位置

mysql - 使用mysql在一个查询中选择多个表中的 child 总数

php - 左连接可选表

sql - 日期时间的 SSIS 源格式隐式转换

MySQL 表索引基数

mysql - #1146 - 表 'phpmyadmin.pma_table_uiprefs' 不存在

php - 比较两个查询 Laravel 的结果