mysql查询是否缓存动态计算的列

时间:2013-09-04 14:44:20

标签: mysql optimization

我有一个mysql查询:

SELECT my_table.* WHERE SOUNDEX(my_col)='whatever' OR SUBSTR(SOUNDEX(my_col),4)='whatever' ORDER BY SUBSTR(SOUNDEX(my_col),4)='whatever',SOUNDEX(my_col)='whatever'

实际调用substring函数和soundex函数的次数是多少?我的意思是,对于完全相同的输入,mysql会在一个查询的范围内缓存结果吗?

如果没有,我如何在查询中进行更改,以便尽可能少地调用每个函数。

1 个答案:

答案 0 :(得分:1)

MySQL会为每个返回的行调用此函数四次,为避免这种情况,您可以使用子查询,因此而不是

  SELECT * 
FROM   song 
ORDER  BY Substr(pre_calculated_soundex, 1, 1) = 
                    Substr(Soundex("aaaa"), 1, 1) 
                                                 + Substr(pre_calculated_soundex 
                    , 2, 1) = 
                    Substr 
                    (Soundex("aaaa"), 2, 1) 
                    + Substr(pre_calculated_soundex, 3, 1) 
                    = Substr(Soundex("aaaa"), 3, 1) 
                      + Substr(pre_calculated_soundex, 4, 1 
                      ) 
                      = Substr(Soundex("aaaa"), 4, 1) 

你可以做到

SELECT *  from (select *, Soundex("aaaa") as current_soundex from song)
ORDER  BY 
            Substr(pre_calculated_soundex, 1, 1) = Substr(current_soundex , 1, 1) 
          + Substr(pre_calculated_soundex, 2, 1) = Substr(current_soundex , 2, 1) 
          + Substr(pre_calculated_soundex, 3, 1) = Substr(current_soundex , 3, 1) 
          + Substr(pre_calculated_soundex, 4, 1) = Substr(current_soundex , 4, 1)