mysql - 避免 UNION RESULT 上出现 "filesort"

标签 mysql indexing query-optimization filesort

子查询1:

SELECT * from big_table
where category = 'fruits' and name = 'apple'
order by yyyymmdd desc

解释:

table       |   key           |   extra
big_table   |   name_yyyymmdd |   using where

看起来很棒!

子查询2:

SELECT * from big_table
where category = 'fruits' and (taste = 'sweet' or wildcard = '*')
order by yyyymmdd desc

解释:

table       |   key               |   extra
big_table   |   category_yyyymmdd |   using where

看起来很棒!

现在,如果我将它们与 UNION 结合起来:

SELECT * from big_table
where category = 'fruits' and name = 'apple'

UNION

SELECT * from big_table
where category = 'fruits' and (taste = 'sweet' or wildcard = '*')

Order by yyyymmdd desc

解释:

table       |   key      |   extra
big_table   |   name     |   using index condition, using where
big_table   |   category |   using index condition
UNION RESULT|   NULL     |   using temporary; using filesort

不太好,它使用文件排序。

这是一个更复杂查询的精简版本,以下是有关 big_table 的一些事实:

  • big_table 有 10M + 行
  • 有 5 个独特的“类别”
  • 有5种独特的“品味”
  • 大约有 10,000 个独特的“名称”
  • 大约有 10,000 个唯一的“yyyymmdd”
  • 我在每个字段上创建了单个索引,以及复合 idx,例如 yyyymmdd_category_taste_name,但 Mysql 没有使用它。

最佳答案

SELECT * FROM big_table
    WHERE category = 'fruits'
      AND (  name = 'apple'
          OR taste = 'sweet'
          OR wildcard = '*' )
    ORDER BY yyyymmdd DESC

并且有 INDEX(catgory) 或一些以 category 开头的索引。但是,如果表中超过 20% 的内容是 category = 'fruits',则可能会决定忽略索引并简单地进行表扫描。 (既然你说只有 5 个类别,我怀疑优化器会正确地避开索引。)

或者这可能是有益的:INDEX(category, yyyymmdd),按这个顺序。

UNION 必须进行排序(无论是在内存中还是在磁盘中,尚不清楚),因为它无法按所需的顺序获取行。

复合索引INDEX(yyyymmdd, ...)可用于避免“文件排序”,但它不会使用yyyymmdd之后的任何列。

构建复合索引时,开始与任何WHERE列进行比较'='。之后,您可以添加一个范围或分组依据排序依据More details .

UNION 通常是避免缓慢的 OR 的不错选择,但在这种情况下,它需要三个索引

INDEX(category, name)
INDEX(category, taste)
INDEX(category, wildcard)

并且添加 yyyymmdd 不会有帮助,除非您添加 LIMIT

查询将是:

( SELECT * FROM big_table WHERE category = 'fruits' AND name = 'apple' )
UNION DISTINCT
( SELECT * FROM big_table WHERE category = 'fruits' AND taste = 'sweet' )
UNION DISTINCT
( SELECT * FROM big_table WHERE category = 'fruits' AND wildcard = '*' )
ORDER BY yyyymmdd DESC

添加限制会更加困惑。首先将 yyyymmdd 固定在三个复合索引的末尾上,然后

( SELECT ... ORDER BY yyyymmdd DESC LIMIT 10 )
UNION DISTINCT
( SELECT ... ORDER BY yyyymmdd DESC LIMIT 10 )
UNION DISTINCT
( SELECT ... ORDER BY yyyymmdd DESC LIMIT 10 )
ORDER BY yyyymmdd DESC  LIMIT 10

添加 OFFSET 会更糟。

另外两种技术——“覆盖”索引和“惰性查找”可能会有所帮助,但我对此表示怀疑。

另一种技术是将所有单词放在同一列中并使用 FULLTEXT 索引。但这可能由于多种原因而存在问题。

关于mysql - 避免 UNION RESULT 上出现 "filesort",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36389302/

相关文章:

php - 将数据发布到 MySql 表时出现问题 - 表仍为空

php - MySQL,目标表可以由查询命名吗?

mysql - 查询查找具有最大运行日期和最大范围的结果

创建特定元素列表的 Pythonic 方法

sql - 简单查询优化

postgresql - 如何改进 Postgresql 中的 UPDATE 查询结果时间?

php - mysql注入(inject)+强制用户使用列表进行数据输入

indexing - 提高单个Elasticsearch索引以使其在结果中具有优先权

python - Tkinter 索引词问题

mysql、关键及优化: does my key seem to be useless?