什么是复合索引,如何正确使用?

时间:2018-10-03 16:05:42

标签: 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; Using index; Using temporary; Using filesort 1 SIMPLE attachments eq_ref PRIMARY PRIMARY 4 quote.to_attachments.attachment_id 1 NULL

to_attachments的索引 enter image description here

2 个答案:

答案 0 :(得分:4)

您要在exec.submit(new ThreadController("processData",list.next())); to_attachments(object_type, object_id, attachment_id)上建立索引。

答案 1 :(得分:1)

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