我的 table 上有足球比赛列表。它有诸如 match_id、球队得分、球队 2 得分、轮数、比赛日期等列。
我需要数据库中该轮利润率最高的所有行 差额是a队得分与b队得分之差。
我的查询是
SELECT *,( SELECT MAX(ABS((z.home_score - z.away_score)))
FROM tblform_matches z
WHERE YEAR(z.match_date) = YEAR(tblform_matches.match_date)
AND z.round = tblform_matches.round ) as highest_margin
from tblform_matches where some condtion
这是一个简化的查询,其中某些条件是一个大查询字符串,用于根据过滤器选择某些指定的匹配项。
目前数据库中有大约 5000 个匹配项。
由于子查询,我的页面加载时间还多了 4 秒。
每轮有9场比赛,每年有20多轮
我正在 php 循环中为每个团队执行上述查询。我无法改变这件事。因为显示统计数据需要进行大量计算。
抱歉,如果我的问题不清楚,如果我错过了一些东西,我会在这里,因为我是 stakoverflow 的新蜜蜂
提前致谢。
最佳答案
这是您的查询:
SELECT m.*,
(SELECT MAX(ABS((m2.home_score - m2.away_score)))
FROM tblform_matches m2
WHERE YEAR(m2.match_date) = YEAR(m.match_date) AND
m2.round = m.round
) as highest_margin
from tblform_matches m
where some condition;
据推测,优化这一点的最佳方法是专注于 .那好吧。您将需要正确的索引。
索引显然是解决方案,但由于 year
函数,您遇到了问题。简单的解决方案是使用不等式:
SELECT m.*,
(SELECT MAX(ABS((m2.home_score - m2.away_score)))
FROM tblform_matches m2
WHERE m2.round = m.round
(m2.match_date >= makedate(year(m.match_date), 1) and
m2.match_date < makedate(year(m.match_date) + 1, 1)
)
) as highest_margin
from tblform_matches m
where some condtion;
子查询的最佳索引是tblform_matches(round, match_date, home_score,away_score)
。前两列用于 where
子句。后两个用于选择
。
注意:如果您对数据结构进行了两个相对较小的更改,则效果可能会更好。添加一列表示比赛日期的年份(多余,但对于索引很重要)。并且,添加一列来表示分数之间差异的绝对值。那么查询将是:
SELECT m.*,
(SELECT MAX(score_diff)
FROM tblform_matches m2
WHERE m2.round = m.round and m2.matchyear = m.matchyear
) as highest_margin
from tblform_matches m
where some condtion;
此查询的索引为:tblform_matches(round, matchyear, Score_diff)
并且查找应该非常快。
编辑:
通过显式加入
,您可能会获得更好的性能:
SELECT m.*, m2.highest_margin
from tblform_matches m join
(select MAX(ABS((m2.home_score - m2.away_score))) as highest_margin
from tblform_matches m2
group by year(m2.match_date), m2.round
) m2
on year(m.match_date) = year(m2.match_date) and m2.round = m.round
where some condition;
关于php - 如何最小化mysql中此查询的响应时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30682722/