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

What is compound indexing and how do I use it properly?

我有一个非常慢的查询,它会重复很多次。我试过为各个字段编制索引,但似乎无济于事。 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; Using index; Using temporary; Using filesort 1 SIMPLE attachments eq_ref PRIMARY PRIMARY 4 quote.to_attachments.attachment_id 1 NULL

to_attachments 的索引

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

你的索引顺序错了,应该是(object_type, object_id, attachment_id)。在多列索引中,索引中列的顺序是 MATTER。