嵌套查询优化

时间:2014-08-14 10:27:31

标签: mysql indexing subquery

我想优化以下类型的查询:

SELECT org, departat, dst, fkey1, fkey2 
FROM (
 (SELECT * FROM (   
    (SELECT org, UNIX_TIMESTAMP(departat) as departat, dst, fkey1, fkey2, price  
     FROM two_legs    
     WHERE org in ( 'AES','AMS','BGO') AND dst = 'MAD' AND UNIX_TIMESTAMP(departat) >= 1409608800 
     LIMIT 100000) 
    UNION ALL 
    (SELECT org, UNIX_TIMESTAMP(departat) as departat, dst, fkey as fkey1, 0 as fkey2, price
     FROM one_legs    
     WHERE org in ( 'AES','AMS','BGO') AND dst = 'MAD' AND UNIX_TIMESTAMP(departat) < 1409695199
    )
  ) a
 ORDER BY price
 LIMIT 1000)
 ) godzilla 
ORDER BY org, departat

解释给出:

id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 358 Using filesort
2 DERIVED <derived3> ALL NULL NULL NULL NULL 358 Using filesort
3 DERIVED two_legs range rd rd 6 NULL 102225 Using where
4 UNION one_legs range PRIMARY PRIMARY 18 NULL 11532 Using where 
NULL UNION RESULT <union3,4> ALL NULL NULL NULL NULL NULL

所以我看到两个filesorts,虽然two_legs和one_legs每个都有两个索引(一个在价格上,一个在org上)。如何避免filesorts?是否值得创建临时表的开销,如果是这样,如何分解查询?

0 个答案:

没有答案