防止在查询中使用临时表

时间:2011-11-07 00:32:19

标签: mysql query-optimization

我正在运行解释扩展以下查询,我不知道为什么会发生这种情况。我在site.id, site.parent_id, and site.enabled上添加了一个索引,但我仍然看到它正在创建一个临时表。

SELECT site.label AS site_label, deal . * , site.id AS site_id
FROM site
LEFT JOIN deal ON ( deal.site_id = site.id
AND DAYOFYEAR( deal.created ) = DAYOFYEAR( NOW( ) ) ) 
WHERE (
site.id =2
OR site.parent_id =2
)
AND site.enabled =1
ORDER BY site.order ASC , deal.created DESC

有关如何防止使用临时表的任何建议吗?

id  select_type table   type    possible_keys   key key_len ref rows    filtered    Extra
1   SIMPLE  site    ALL id,parent_id,id_2   NULL    NULL    NULL    10  100.00  Using where; Using temporary; Using filesort
1   SIMPLE  deal    ref site_id site_id 4   dealclippings.site.id   235 100.00   

1 个答案:

答案 0 :(得分:2)

执行无法优化的查询:

  1. 尽量避免使用OR
  2. Mysql无法优化(使用索引)进行不同方向的排序(在一个ASC中同时使用DESCORDER BY
  3. DAYOFYEAR( deal.created )避免在您按
  4. 搜索的字段上使用功能

    但是,在您对查询性能感到满意之前,您不应该知道temporary table标签,或者不是吗?

相关问题