sql - 优化 groupBy 查询
问题描述
我有两张桌子 A 和 B。A 有id, startDate, endDate
. 乙有id, date, count
。目标是获得每个条目之间startDate
的最大计数。endDate
A
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, endDate
for tableA
和id, date
for table上有索引B
。行数A
约为 10K,而 inB
为 200 万。上述查询大约需要 5-6 秒才能完成。谁能建议我可以尝试的东西?
解决方案
这是您的查询:
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 ;
为此,您肯定需要上述索引。
推荐阅读
- userscripts - 如何根据设置构建图表Charts.ChartType.COMBO?
- flutter - 如何测试 Flutter web 的浏览器 url 路由?
- angular - 如何在具有纬度和经度的 Angular Highchart 地图中绘制点?
- r - R 显示的数字太少
- class - 运行类的方法时,我收到“意外令牌:(”错误消息
- python - 平均值和克矩阵
- email - 使用 Google 表格和 Google Apps 脚本创建 PDF 文件
- json - 颤振Json文件中的值总和
- javascript - 未添加事件侦听器
- typescript - Vue 3 我可以获得应用于组件的自定义指令列表吗?