2016-07-06 59 views
0

兩個表我試圖連接兩個表:SQL JOIN與AVG

songs 
id | song | artist 
---|------|------- 
1 | foo | bar 
2 | fuu | bor 
3 | fyy | bir 

score 
id | score 
---|------ 
1 | 2 
2 | 4 
3 | 8 
2 | 6 
3 | 2 

使用此SQL命令:

SELECT songs.id, songs.song, songs.artist, score.score FROM songs LEFT JOIN score ON score.id=songs.id ORDER BY songs.id, score DESC 

我得到的回覆是有多個得分同一首歌的副本,我希望得分是平均的。

result 
id | song | artist | score 
---|------|--------|------- 
1 | foo | bar | 2 
2 | fuu | bor | 4 
2 | fuu | bor | 6 
3 | fyy | bir | 8 
3 | fyy | bir | 2 

我試過用:

SELECT songs.id, songs.song, songs.artist, ROUND(AVG(score.score),1) AS 'score' FROM songs INNER JOIN score ON score.id=songs.id ORDER BY score DESC 

但是,平均所有得分,而不僅僅是得分每一個人首歌曲的

result 
id | song | artist | score 
---|------|--------|------- 
1 | foo | bar | 4.4 
+1

添加'集團By' .. –

+0

成績沒有主鍵,這可能證明是有問題。 – Strawberry

回答

3

您需要GROUP BY所有字段要保留:

SELECT songs.id, songs.song, songs.artist, 
    AVG(score.score * 1.0) AS AvgScore 
FROM songs 
    LEFT JOIN score 
     ON score.id=songs.id 
GROUP BY songs.id, songs.song, songs.artist 
ORDER BY songs.id, score DESC 

或者,你可能只是這樣做:

SELECT songs.id, songs.song, songs.artist, 
    (SELECT AVG(Score) FROM score WHERE score.id = songs.id) AS AvgScore) 
FROM songs 
0

使用 「組由」 songs.id

SELECT songs.id, songs.song, songs.artist, 
    ROUND(AVG(score.score),1) AS 'score' FROM songs 
    INNER JOIN score ON score.id=songs.id 
group by songs.id ORDER BY score DESC 
+0

不需要在每個答案中都說出來。 OP問問題獲得答案,所以他肯定會嘗試。沒有刺耳的感情;) –

+0

@Prdp:我刪除它。但在大多數情況下,我們沒有得到任何答覆,至少它的工作或沒有:( –

0

使用此 選擇a.id,a.song,一.artist,avg(b.score)作爲歌曲評分a內部加入評分b對a.id = b.id 分組a.id,a.artist,a.song

0

您需要GROUP BY並加入數據向左(JOIN LEFT

試試這個:

SELECT 
    songs.id, 
    songs.song, 
    songs.artist, 
    ROUND(AVG(score.score), 1) AS 'score' 
FROM songs 
LEFT JOIN score ON score.id = songs.id 
GROUP BY songs.id 
ORDER BY score DESC