简体   繁体   English

如何在简单的MySQL查询中设计索引/查询以避免文件排序?

[英]How to design an index/query to avoid filesort in a simple MySQL query?

I have a table entrytable , that has the colums datum , username , status , status_spam_user , status_spam_system and text . 我有一个表entrytable表,它有colums datumusernamestatusstatus_spam_userstatus_spam_systemtext

I want to select the content of the column text, from rows that have certain values for username , status , status_spam_user , status_spam_system . 我想从具有usernamestatusstatus_spam_userstatus_spam_system特定值的行中选择列文本的内容。 Since this can result in a long list of entries (>30'000) I want to limit the number of matching rows. 由于这会导致一长串条目(> 30'000),我想限制匹配行的数量。 Before I to that, the matching rows should be ordered by the column datum . 在此之前,匹配的行应按列datum排序。

SELECT text
FROM entrytable
WHERE user = 'username' &&
`status` = '1' && (
    `status_spam_user` = 'no_spam'
    || (
        `status_spam_user` = 'neutral' &&
        `status_spam_system` = 'neutral'
    )
)
ORDER BY datum DESC
LIMIT 6430 , 10

I added two indices to the table: 我在表格中添加了两个索引:

  • index_datum (datum) index_datum(datum)
  • index_status_mit_spam (user, status, status_spam_user, status_spam_system) index_status_mit_spam(user,status,status_spam_user,status_spam_system)

For this query the index index_status_mit_spam is used. 对于此查询,使用索引index_status_mit_spam Since the index does not contain information of the column datum , the sorting has to be does separately (ie filesort). 由于索引不包含列datum ,因此排序必须单独进行(即filesort)。 Is it possible to design my query/index in a way, that it is useful for the WHERE as well as for ORDER BY ? 是否有可能以某种方式设计我的查询/索引,它对WHERE以及ORDER BY有用吗?

在status_spam_user / status_spam_system上添加一个索引on (user, status, datum)索引因为OR条件(它被用于状态部分)而无法使用,并且必须在之前使用索引的所有先前部分按部分排序可以满足索引

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

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