【发布时间】: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