简体   繁体   English

MySQL相同的查询导致多个子查询

[英]MySQL same query result in multiple subqueries

I am trying to optimize following query. 我正在尝试优化以下查询。

SELECT t3.*, 
        (SELECT SUM(t4.col_sum)
            FROM (...) t4
            WHERE t4.timestamp BETWEEN CONCAT(SUBSTR(t3.timestamp, 1, 11), "00:00:00") AND t3.timestamp)
        AS cum_sum
FROM (...) t3

Where (...) is a container for long query. 其中(...)是用于长时间查询的容器。 It results 2 columns: timestamp and col_sum. 结果为2列:timestamp和col_sum。 I want to add third column to it by writing a query. 我想通过编写查询来添加第三列。 That third column is a cumulative sum of col_sum. 第三列是col_sum的累加和。

The problem is I am putting same big query in two places (...) 问题是我将相同的大查询放在两个地方(...)

Is there a way I can obtain a result and use the result in those two/multiple places (...)? 有什么方法可以获取结果并在两个/多个地方使用结果(...)?

One method is to use a temporary table. 一种方法是使用临时表。

Probably a more efficient method is to use variables to calculate a cumulative sum. 可能更有效的方法是使用变量来计算累积和。 It would be something like: 就像这样:

  select t.*,
         (@c := if(@t = left(t.timestamp, 11), @c + t.col_sum,
                   if(@t := left(t.timestamp, 11), 0, 0)
                  )
         ) as cumesum
  from (. . .) t cross join
       (select @t := '', @c := 0) vars
  order by t.timestamp;

The above query orders the rows by timestamp . 上面的查询按timestamp对行进行timestamp The variable @t keeps track of the first 11 characters in the timestamp -- as I read your logic, you want to do the cumulative sum only within a group where this is constant. 变量@t跟踪时间戳中的前11个字符-在我阅读您的逻辑时,您只想在恒定的组中进行累积和。

The variable @c keeps track of the cumulative sum, resetting to zero when a new "first 11 characters" are encountered. 变量@c跟踪累积和,在遇到新的“前11个字符”时重置为零。 The logic looks a bit complicated, but it is best to put all variable assignments in a single expression, because MySQL does not guarantee the order of evaluation of expressions. 逻辑看起来有些复杂,但是最好将所有变量赋值放在一个表达式中,因为MySQL不能保证表达式求值的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM