0

我有一个非常慢的查询,它会重复很多次。我试过索引各个字段,但似乎没有帮助。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 的索引 在此处输入图像描述

4

2 回答 2

4

你想要索引to_attachments(object_type, object_id, attachment_id)attachments(id)

于 2018-10-03T16:07:55.617 回答
1

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

于 2018-10-03T16:24:05.627 回答