使用LEFT JOIN在查询中添加列

时间:2016-07-24 10:01:33

标签: mysql sql select average

我有三张桌子。

tblcandidates

candidateid     |     candidatename
1               |     Abc
2               |     Def

tbljudges

judgeid         |     judgename
1               |     Stack
2               |     Overflow

tblscores

scoreid         |     candidateid     |     judgeid     |     swimsuit
1               |     1               |     1           |     100
2               |     1               |     2           |     99
3               |     2               |     1           |     100
4               |     2               |     2           |     93

我正在使用此查询来获取每位候选人的平均值。

SELECT DISTINCT
    (c.candidateid) AS c,
    candidatename AS NAME,
    j1.swimsuit AS j1,
    j2.swimsuit AS j2,
    (
        j1.swimsuit + j2.swimsuit
    ) / 2 AS average
FROM
    tblscores,
    tblcandidates c
LEFT JOIN tblscores j1 ON c.candidateid = j1.candidateid
AND j1.judgeid = 1
LEFT JOIN tblscores j2 ON c.candidateid = j2.candidateid
AND j2.judgeid = 2
WHERE   tblscores.candidateid = c.candidateid;

输出

c      |      name       |      j1       |      j2       |     average
1      |      Abc        |      100      |      99       |     99.5
2      |      Def        |      100      |      93       |     96.5

如果评委变为3,我的问题就是如何。我想根据评委的数量使我的查询动态。我的查询仅限2名法官。我还希望在我的输出中显示评委分数,以证明他们有分数。

1 个答案:

答案 0 :(得分:3)

您正在通过自己实施平均计算来重新发明轮子。相反,您可以使用MySQL的内置聚合avg功能。如果您真的想要所有分数,可以使用group_concat来显示它们:

SELECT   c.candidateid AS id, 
         candidatename AS name,
         GROUP_CONCAT(swimsuit) AS all_scores,
         AVG(swimsuit) AS average_score
FROM     tblcandidates c 
JOIN     tblscores s ON c.candidateid = s.candidateid
GROUP BY c.candidateid, candidatename