简体   繁体   English

为什么此查询不对ORDER BY使用索引?

[英]Why does this query doesn't use index for ORDER BY?

SELECT `f`.*
FROM `files_table` `f`
WHERE f.`application_id` IN(6)
AND `f`.`project_id` IN(130418)
AND `f`.`is_last_version` = 1
AND `f`.`temporary` = 0
AND f.deleted_by is null
ORDER BY `f`.`date` DESC
LIMIT 5

When I remove the ORDER BY, query executes in 0.1 seconds. 当我删除ORDER BY时,查询将在0.1秒内执行。 With the ORDER BY it takes 3 seconds. 使用ORDER BY需要3秒钟。

There is an index on every WHERE column and there is also an index on ORDER BY field (date). 在每个WHERE列上都有一个索引,在ORDER BY字段(日期)上也有一个索引。

What can I do to make this query faster? 我怎样做才能使查询更快? Why is ORDER BY slowing it down so much? 为什么ORDER BY放慢速度呢? Table has 3M rows. 表格有3M列。

instead of an index on each column in where be sure you have a composite index that cover all the columns in where 而不是在每个列的索引,请确保您有一个复合索引来覆盖其中的所有列

eg 例如

create index  idx1 on files_table (application_id, project_id,is_last_version,temporary,deleted_by)

avoid IN clause for single value use = for these 避免IN子句用于单值use =对于这些

  SELECT `f`.*
  FROM `files_table` `f`
  WHERE f.`application_id`  = 6 
  AND `f`.`project_id` = 130418
  AND `f`.`is_last_version` = 1
  AND `f`.`temporary` = 0
  AND f.deleted_by is null
  ORDER BY `f`.`date` DESC
  LIMIT 5

the date or others column in select could be useful retrive all info using the index and avoiding the access to the table data .. but for select all (select *) you probably need severl columns an then the access to the table data is done however .. but you can try an eval the performance .. select中的date或others列可能很有用,它使用索引来检索所有信息并避免访问表数据..但是对于全选(select *),您可能需要多个列,然后完成对表数据的访问..但您可以尝试评估表演..

be careful to place the data non involved in where at the right of all the column involved in where 注意将不涉及的数据放置在所有涉及的列的右侧

create index  idx1 on files_table (application_id, project_id,is_last_version,temporary,deleted_by, date)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM