我有一个包含3个表的数据库:
股票和股票分割之间,以及股票和股息之间存在一对多的关系。对于每个股票,我想显示股票分割和股息的数量:
SELECT equities.Symbol,
(SELECT COUNT(*)
FROM stocksplits
WHERE stocksplits.EquityID = equities.InstrumentID) as `# Splits`,
(SELECT COUNT(*)
FROM dividends
WHERE dividends.EquityID = equities.InstrumentID) as `# Dividends`
FROM equities
该查询似乎运行良好,尽管我怀疑它效率低下。如何将其重构为更快?没有DBMS(通过.net到MySQL服务器的SQL查询),假定每个表的主ID上都存在索引。
最佳答案
计算PK而不是*可能已经有所帮助:
SELECT equities.Symbol,
(SELECT COUNT(stocksplitsID)
FROM stocksplits
WHERE stocksplits.EquityID = equity.InstrumentID) as `# Splits`,
(SELECT COUNT(dividendsid)
FROM dividends
WHERE dividends.EquityID = equities.InstrumentID) as `# Dividends`
FROM equities