首页 > 解决方案 > 优化 groupBy 查询

问题描述

我有两张桌子 A 和 B。A 有id, startDate, endDate. 乙有id, date, count。目标是获得每个条目之间startDate的最大计数。endDateA

select a.id, a.startDate, a.endDate, max(b.count)
from A a join B b
  on a.id=b.id
 and b.date>=a.startDate
 and b.date<=a.endDate
group By a.id, a.startDate, a.endDate;

例如

A -> (1,2016-01-01,2016-01-03)

B -> (1,2016-01-01,1),(1,2016-01-02,4),(1,2016-01-03,3),(1,2016-01-04,2)

查询结果 -> (1,2016-01-01,2016-01-03,4)这里 4 是 (1,4,3) 的最大值

我在id, startDate, endDatefor tableAid, datefor table上有索引B。行数A约为 10K,而 inB为 200 万。上述查询大约需要 5-6 秒才能完成。谁能建议我可以尝试的东西?

标签: sqlgroup-bymariadbaggregate-functions

解决方案


这是您的查询:

select a.id, a.startDate, a.endDate, max(b.count)
from A a join
     B b
     on a.id = b.id and
        b.date >= a.startDate and
        b.date <= a.endDate
group By a.id, a.startDate, a.endDate;

开始的地方是一个索引b(id, date, count)。这可能会有所帮助。但是,查询引擎仍在对整个a表进行聚合——这很昂贵。

通常,相关子查询效果更好:

select a.id, a.startDate, a.endDate, 
       (select max(b.count)
        from B b
        where a.id = b.id and
              b.date >= a.startDate and
              b.date <= a.endDate
       ) as count
from A a ;

为此,您肯定需要上述索引。


推荐阅读