0

我在 MySQL 中有一个查询,看起来像这样:

SELECT t.field1, t.field2, t.field5, t.field6, t.field7 
FROM mytable as t  

WHERE t.field1 = a AND t.field2 = b AND t.field3 = c AND LENGTH(t.field4) > 0

order by t.field5 desc

LIMIT 0, 100;

查询不是很快(10 秒),问题似乎是 ORDER BY 部分,如果没有该行,查询需要 0.01 秒,使用 ASC 而不是 desc 大约需要 1 秒。

我已经创建了一个索引,其中查询的 WHERE/ORDER BY 部分中的所有字段的顺序与它们在查询中出现的顺序相同(field1、field2、field3、field4、field5),但它没有根据“解释”使用“在 MySQL 中。

field1 具有相当高的基数(具有大约 100 个不同值的整数) field2 和 field3 是 BOOLEAN 并且 field5 是具有高基数的字符串(但是 LENGTH(field5) > 0 使得基数低,或者?)。

在 field5 上也有一个索引,当查询看起来像上面时,这是唯一使用的索引,删除查询的 ORDER BY 部分将使 MySQL 使用多列索引。

我在这里想念什么?

编辑:这是实际的 SQL:

SELECT t.shopid, t.isproduct, t.level, t.isduplicate, t.ref_id 

FROM urls as t

WHERE t.shopid = 72 AND t.isproduct = 1 AND t.visited = 0 AND LENGTH(t.url) > 0  

ORDER BY t.level desc

LIMIT 0, 100;
4

1 回答 1

0

在不实际知道表大小和数据类型的情况下很难预测查询性能。Mysql 优化器有自己的方法来决定使用哪个索引,这通常是相当不错的。您可以通过强制 mysql 使用各种索引来进行命中和试验FORCE INDEX。由于显而易见的原因,永远不能使用 t.url 上的索引。

您可以尝试的一件事是:

select t.field1, t.field2, t.field5, t.field6, t.field7 from (SELECT t.field1, t.field2, t.field5, t.field6, t.field7 FROM mytable as t WHERE t.field1 = a AND t.field2 = b AND t.field3 = c AND LENGTH(t.field4) > 0) t order by t.field5 desc LIMIT 0, 100;

通常不建议这样做,但如果输出行数不大,则可以为您提供帮助。

于 2013-10-15T11:58:06.013 回答