所以有两个查询。为什么第一次运行速度比第二次快?如何优化内连接的速度与第一个一样快?
总记录超过4 000 000
idTerminals已编入索引
select (select name
from terminals
where terminals.idTerminals = AnalyzeProfitResults.idTerminals),
currency,
count(*)
from AnalyzeProfitResults
group by AnalyzeProfitResults.idTerminals,currency;
select name,
currency,
count(*)
from AnalyzeProfitResults
inner join terminals on terminals.idTerminals = AnalyzeProfitResults.idTerminals
group by AnalyzeProfitResults.idTerminals,currency;
结果相同:
name,currency,count(*)
"Buy or sell",EURUSD,235105
"Buy or sell",GBPUSD,14515
"Buy or sell",USDJPY,235298
"very strict",AUDJPY,234787
"very strict",AUDUSD,235298
"very strict",CHFJPY,235298
"very strict",EURJPY,235298
"very strict",EURUSD,235298
"very strict",GBPJPY,235298
"very strict",GBPUSD,235298
"very strict",NZDUSD,235298
"very strict",USDCHF,235298
"very strict",USDJPY,235298
",normal",AUDJPY,235298
",normal",AUDUSD,36391
",normal",EURUSD,234985
",normal",GBPJPY,117649
",normal",NZDUSD,198552
",normal",USDCHF,235298
",normal",USDJPY,235298
答案 0 :(得分:1)
我想在后一个查询中,MySQL加入AnalyzeProfitResults
和terminals
,为size(AnalyzeProfitResults) * size(terminals)
操作产生group by
行。在AnalyzeProfitResults
中有400万行,即使terminals
只包含少量记录,也会有很多行。在前一种情况下,MySQL在400万行上执行分组,产生你给出的20行行,然后只对20行中的每一行执行子查询(甚至可以在内部重写为连接,这将是偶数快)。
修改强> 这是第一个带有显式连接的查询:
select terminals.name, APR_aggregated.*
from terminals join (
select APR.currency, count(*)
from AnalyzeProfitResults as APR
group by APR.idTerminals, APR.currency
) as APR_aggregated on terminals.idTerminals = APR_aggregated.idTerminals