SQL JOIN 两个表与 AVG

Lud*_*ann 1 mysql sql join average

我正在尝试加入两个表:

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
Run Code Online (Sandbox Code Playgroud)

使用此 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
Run Code Online (Sandbox Code Playgroud)

我得到的是具有多个分数的同一首歌的重复,我希望分数是平均的。

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
Run Code Online (Sandbox Code Playgroud)

我尝试使用:

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
Run Code Online (Sandbox Code Playgroud)

但这是所有分数的平均值,而不仅仅是每首歌曲的分数

result
id | song | artist | score
---|------|--------|-------
1  | foo  | bar    | 4.4
Run Code Online (Sandbox Code Playgroud)

Joh*_*uet 5

您需要对要保留的所有字段进行 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
Run Code Online (Sandbox Code Playgroud)

或者,您可以这样做:

SELECT songs.id, songs.song, songs.artist, 
    (SELECT AVG(Score) FROM score WHERE score.id = songs.id) AS AvgScore)
FROM songs 
Run Code Online (Sandbox Code Playgroud)