2016-07-24 198 views
1

我有三個表。使用LEFT JOIN在查詢中添加列

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名評委。我還想顯示評分得分,就像我輸出的結果一樣,以證明他們有得分。

+2

請分享一個sql小提琴。這是一個MySQL數據透視表問題。 – 1000111

+0

如何製作一個sql小提琴? –

+0

下面是一個示例[** sql fiddle **](http://sqlfiddle.com/#!9/3fd52/1/0) – 1000111

回答

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 
+0

對不起。我忘了我也必須顯示所有的評委分數。就像我的輸出一樣。 –

+0

@SeeMore'group_concat'調用將顯示所有單獨的分數。如果你在不同的欄目中需要他們,你別無選擇,只能繼續添加更多項目到你的選擇清單中,就像你迄今爲止所做的那樣。 – Mureinik

+1

好吧..我試過了。所有的分數都以逗號分隔,謝謝..也許我現在只是用爆炸來讓他們全部用php。我會等待一些其他答案,但你的答案是有幫助的。謝謝。 –