简体   繁体   English

在MySQL查询中使用OR时,有没有办法使用索引来避免文件排序?

[英]Is there a way to use the index to avoid a filesort when OR is used in MySQL query?

I have the following query and the following 2 indexes, but I am still getting a filesort. 我有以下查询和以下2个索引,但我仍然得到一个文件排序。 Is there a way to optimize this further so that I avoid the filesort, or do I just need to live with it? 有没有办法进一步优化这个以避免文件排序,或者我只需要忍受它?

Query: 查询:

SELECT * FROM table WHERE row1 > '0' OR row2 = '1' ORDER BY id DESC

Indexes: 索引:

row1 ROW1

row2,id ROW2,ID

EXPLAIN output: EXPLAIN输出:

Using sort_union(row1,row2_id); 使用sort_union(row1,row2_id); Using where; 用在哪里; Using filesort 使用filesort

ORDER BY ROW2,ID或在ID上添加索引。

Yes, you can. 是的你可以。 Just add index like (id, row1, row2). 只需添加索引(id,row1,row2)。

This index will work, because rows in it will be pre-sorted and mySQL will only need to select the satisfying lines. 这个索引可以工作,因为它中的行将被预先排序,而mySQL只需要选择令人满意的行。

Moreover, sort_union() index merging is not THAT good optimization for mySQL anyway. 而且,sort_union()索引合并对于mySQL来说并不是很好的优化。

It's a little bit late for answering but i want to say that, using "or" probably causing that problem. 回答有点迟,但我想说,使用“或”可能导致这个问题。 You can try using union with two different queries. 您可以尝试使用带有两个不同查询的union。

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

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