【问题标题】:Store mysql variable in a group by and use in statement to prevent duplicate calculation将mysql变量存储在group by并在语句中使用以防止重复计算
【发布时间】:2021-11-06 01:06:52
【问题描述】:

给定一个示例查询,例如

SELECT IF(
        ABS(sum(grades) / count(*) * 100) < 1,
        ROUND(sum(grades) / count(*) * 100, 2),
        IF(ABS(sum(grades) / count(*) * 100) < 10,
            ROUND(sum(grades) / count(*) * 100, 1),
            ROUND(sum(grades) / count(*) * 100, 0)
        )
)
from important_table
group by timestamp

是否可以不必每次分组计算总和 3 次,而是预先将 sum(grades) / count(*) * 100 存储在一个变量中,仍然按时间戳分组,并在查询中使用它?这看起来有点脏,而且对我来说是重复的。

这是一个真正的优化可能性吗?还是mysql在执行查询时无论如何都会缓存它?

【问题讨论】:

  • 永远不要使用count(*),而是使用count(1)。它要快得多。另外,看看mysqlAVG函数

标签: mysql variables optimization


【解决方案1】:

我不会担心重新计算这些值。如果需要,SQL 优化器可以决定只计算一次(尽管我认为 MySQL 优化器不会这样做)。

但是,假设grades 不是NULL,您可以使用avg() 来简化表达式:

select (case when ABS(avg(grades) * 100) < 1
             then ROUND(avg(grades) * 100, 2)
             when ABS(avg(grades) * 100) < 10
             then ROUND(avg(grades) * 100, 1)
             else ROUND(avg(grades) * 100, 0)
        end)
from important_table
group by timestamp;

【讨论】:

    猜你喜欢
    • 2012-06-15
    • 1970-01-01
    • 2021-11-21
    • 2012-09-24
    • 2011-10-23
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    相关资源
    最近更新 更多