【问题标题】:Select first row from join with grouped data从加入分组数据中选择第一行
【发布时间】:2017-01-13 10:52:23
【问题描述】:

我有两个单独的查询,我正在尝试有效地加入它们。

Query 1:
Select Id From Accounts Where Status='OPEN' and Product = 'Product A'


Query 2: 
Select AccountId From Transactions Group By AccountId Having Count(*) > 20;

表事务包含数百万行。

我想要实现的是返回第一个处于打开状态的帐户,产品 A 有超过 20 笔交易。

到目前为止我得到了这个,但是由于事务表的全表扫描,它不是很有效:

Select A.Id From Accounts A 
Left Outer Join (Select AccountId From Transactions Group By AccountId Having Count(*) > 20 ) T on A.Id=T.AccountId
Where A.Status='OPEN' and A.Product = 'Product A'
And rownum = 1

如何优化此查询?

【问题讨论】:

  • 事务有索引吗?如果没有,创建一个会提高性能
  • transactions.accountid 已编入索引。表还使用每个月的唯一键进行分区。

标签: sql oracle oracle11g greatest-n-per-group


【解决方案1】:

过滤特定帐户和分组会更好吗?

Select AccountId From Transactions where AccountId in (Select id From Accounts Where Status='OPEN' and Product = 'Product A') Group By AccountId Having Count(*) > 20;

【讨论】:

  • 成本/基数仍然很高。
  • @MrM - 但这不是问题,不是吗?问题是,“这个答案是否比您的原始查询更好。”答案并不明显,它可以根据您的实际数据进行。 Srikanth 答案的基数是否只有您最初尝试的基数的 70%?太好了,它可以为您节省 30% 的时间和资源!您可能无法在 0.001 秒内查询到数百万行的表,连接、分组和计数,这是一个不合理的期望。
猜你喜欢
  • 2015-10-10
  • 2020-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
相关资源
最近更新 更多