是否有任何快速的方法来查询自己在mysql中排除的平均值

时间:2017-08-01 07:52:07

标签: mysql performance

对于下面的表名:team_score

----------------------------
Team    score   date
----------------------------
A       1       2017-07-01 
B       2       2017-07-02
A       3       2017-07-02
B       4       2017-07-01
C       5       2017-07-02
C       6       2017-07-01

获取此表

-------------------------------------
team    avg     avg_excluding_itself 
-------------------------------------
A       2.0     4.25 
B       3.0     3.75 
C       5.5     2.50 

什么是最有效的方式?

下面的查询将无法正常工作,因为它太耗费资源。桌面成像为100GB。

select a.team, avg(a.score) as avg, avg(b.score) as avg_excluding_itself
from team_score a join team_score b on a.team <> b.team group by a.team

1 个答案:

答案 0 :(得分:0)

两个原则:

  • 平均值是除以计数的总和。

  • &#34;不包括&#34;可以通过取整个总数减去要排除的数来计算。

收率:

SELECT
        team,
        ROUND(sum_me / count_me, 1) AS "Team's avg",
        ROUND((sum_all - sum_me) / (count_all - count_me), 2) AS "Avg of others"
    FROM ( SELECT team,
                  SUM(score) AS sum_me,
                  COUNT(*) AS count_me
               FROM team_score
               GROUP BY team ) AS me
    JOIN ( SELECT SUM(score) AS sum_all,
                  COUNT(*) AS count_all
               FROM team_score ) AS x   -- only one row
    GROUP BY team;

将有两个表扫描,每个子查询一个;这样效率太低了。