【问题标题】:MySQL: If I use a function in SQL query more than one time will it get re-calculated every time?MySQL:如果我在 SQL 查询中多次使用一个函数,每次都会重新计算它吗?
【发布时间】:2013-04-22 16:54:52
【问题描述】:

在 MySQL 中,给定以下查询:

select column1
, column2
, my_function1(column3) as f1
, my_function2(column4) as f2
, my_function3 (my_function1(column3), my_function2(column4)) as f3
where some condition on column 1 
having f1 > some value

my_function1(column3) 会被调用 3 次吗? 还是有一些优化/缓存可以重用计算值?

谢谢

【问题讨论】:

    标签: mysql function


    【解决方案1】:

    这是一个简短的实验,看看会发生什么。

    create function determin_rand (i integer) 
    returns float DETERMINISTIC
    return rand();
    
    create function not_determin_rand (i integer) 
    returns float 
    return rand();
    
    select determin_rand(1) as d1 , determin_rand(1) as d2, 
      not_determin_rand(1) as nd1, not_determin_rand(1) as nd2
    
    0.00850549154   0.831901073456  0.133989050984  0.174242004752
    

    由于值不同,因此每次都会调用该函数。在第一个函数中,我声明它是确定性的,但它没有任何区别。

    我为你制作了一个 sqlfiddle 来尝试使用不同版本的 mysql。

    http://sqlfiddle.com/#!2/a8536/2

    【讨论】:

      【解决方案2】:

      每个计算都会分别调用该函数。您可以在单个查询中多次重复使用它。

      【讨论】:

        【解决方案3】:

        除非声明为确定性,否则您的函数将被调用 3 次,但这取决于您的 MySQL 版本,我不太确定该函数是否会被调用一次,如果您想了解更多信息,请阅读此处:http://dev.mysql.com/doc/refman/5.6/en/create-procedure.html

        【讨论】:

          猜你喜欢
          • 2020-10-04
          • 1970-01-01
          • 2015-12-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多