【问题标题】:Does mutliple functions in GROUP BY like concat or cast or dateformat affect the query time?GROUP BY 中的多个函数,如 concat 或 cast 或 dateformat 是否会影响查询时间?
【发布时间】:2025-12-22 06:35:10
【问题描述】:

我有一个查询需要更多时间来执行。我正在尝试优化它。 GROUP BY 中有一些函数可能会增加查询时间。所以我想弄清楚如何优化那部分。

我正在使用 Mysql 5.5.17。

我不能使用强制索引,因为我正在使用 Hibernate,所以这是不可能的。

我还有其他一些选择,例如:

1) 在 group by 中使用别名代替 concat(...)。

2) 或将 concat() 替换为其中的列。

例如:按 concat(1,2,3.) 分组 => 按 1,2,3 分组

在尝试了上述两个选项后,我看不出“查询成本”有什么不同

查询看起来像这样(表名已更改):

    select  sum(this_.a + this_.b + this_.c + this_.d + this_.e +
                this_.f + this_.g + this_.h + this_.i + this_.j) as sent,
        sum(this_.a + this_.b + this_.c + this_.d + this_.e) as delivered,
        d2_.name as y2_, d2_.id as y3_, concat(cast(b4_.id as char),
               '.',c1_.name,'.',cs5_.name,'_',date_format(b4_.createddate,
                       '%Y-%b-%d %H:%i:%s')
                          ) as allias_concat, b4_.id as y5_,
        this_.year as y6_, this_.month as y7_, this_.day as y8_,
        this_.weekday as y9_, this_.weekofmonth as y10_,
        this_.bltid as y11_,
        b4_.id as y12_, c1_.name as y13_,
        cs5_.name as y14_, b4_.createddate as y15_,
        cs5_.subject as y16_, d2_.name as y17_
    from  TABLE1 this_
    inner join  TABLE2 c1_   on this_.cgnid=c1_.id
    inner join  TABLE3 b4_   on this_.bltid=b4_.id
    inner join  TABLE4 csc6_ on b4_.schdlid=csc6_.id
    inner join  TABLE5 cs5_  on this_.constid=cs5_.id
    left outer join  TABLE6 f3_ on this_.fid=f3_.id
    inner join  TABLE7 d2_ on this_.dptid=d2_.id
    where  (f3_.name<>'TRASH'
              or  c1_.fid=0
           )
      and  c1_.status<>'K'
      and  d2_.id in (1)
      and  ((b4_.createddate between '2015-02-01 10:30:00'
                                 AND '2015-05-13 10:29:59'
                      and  csc6_.isrealtime = 'N'
                          )
              or  (csc6_.isrealtime = 'Y'
                      and  this_.bltdate between '2015-02-01 10:30:00'
                                             AND '2015-05-13 10:29:59')
           )
    group by  d2_.id,
              concat(cast(b4_.id as char),'.',c1_.name,'.',cs5_.name,'_',
                     date_format(b4_.createddate,'%Y-%b-%d %H:%i:%s')
                    ),
              b4_.id,
              this_.year, this_.month, this_.day,
              this_.bltid
    limit  20001 

请建议...

提前致谢...

【问题讨论】:

    标签: mysql function group-by query-optimization


    【解决方案1】:

    对不起,但这将是一个“反答案”...

    闻起来像“过度标准化”。例如,感觉就像b4_ 是日期时间(createddate)的规范化,仅此而已。它是否正确?如果是这样,那就会增加复杂性并减慢WHEREGROUP BY 的速度,并消除一些优化的可能性。

    “功能”不是问题。由于GROUP BY 中的项目来自不同的表,因此没有 方法可以对其进行优化。 GROUP BY 必须从各个表中收集信息,将它们放入临时表中,对其进行排序,然后对其进行扫描。 (或类似的东西。关键是没有捷径。)

    “我不能使用 ... 因为我正在使用 Hibernate”——又一个第 3 方软件“妨碍”的情况。如果您无法更改查询,我们将无法帮助您。

    【讨论】:

    • 我如何将 GROUP BY 中的 concat 函数替换为以逗号分隔的方式使用的列。
    • 由于 GROUP BY 中的项目来自不同的表,因此无法对其进行优化。替换 concat 可能会产生微乎其微的影响。