优化group-by-on-join

omhiaaxx  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(253)
SELECT 
 h1.Date AS Date,
 h1.Currency AS Currency1,
 h2.Currency AS Currency2,
 h1.Account AS Account,
 SUM(h1.Size) AS Size1,
 SUM(h2.Size) AS Size2,
 h1.MaturityDate AS MaturityDate
FROM
 htable h1 JOIN htable h2 ON 
 h1.AssetClass = 'FX' AND
 h2.AssetClass = 'FX' AND
 h1.Date = h2.Date AND
 (SUBSTR(h1.Ticker, 7, 3) <> h1.Currency) AND
 (SUBSTR(h2.Ticker, 7, 3) = h2.Currency) AND
 h1.SecID = h2.SecID
GROUP BY h1.Date, h1.Currency, h2.Currency, h1.Account, h1.MaturityDate
HAVING SUM(h1.Size) <> 0 AND SUM(h2.Size) <> 0)

当查询特定日期时,上面没有GROUPBY子句的查询是快速的。
问题是,当我添加groupby时,它会变得非常慢,即使我在having子句中添加了特定的日期。
我已经为htable添加了date、assetclass、secid、currency、duritydate列的索引,以及(date、account、currency、duritydate)组合的索引。
这是在mysql中完成的。关于如何加快查询的速度,您有什么建议吗(我计划将查询用于视图定义)?谢谢!

bgtovc5b

bgtovc5b1#

我想到的第一个可以提高查询性能的索引是:

htable (AssetClass, Date, SecID) -- if Date is more selective than SecID

或者

htable (AssetClass, SecID, Date) -- if SecId is more selective than Date

现在,如果您想更进一步,可以为 SUBSTR(h2.Ticker, 7, 3) ,作者:

alter table htable add ticker_currency varchar(3) 
  generated always as (SUBSTR(h2.Ticker, 7, 3)) virtual;

然后,添加索引:

htable (AssetClass, SecID, Date, ticker_currency)

相关问题